绝对位置,但相对于父位置

本文翻译自:Position absolute but relative to parent

I have two divs inside another div, and I want to position one child div to the top right of the parent div, and the other child div to the bottom of the parent div using css. 我在另一个div内有两个div,我想使用css将一个子div定位到父div的右上角,另一个子div定位到父div的底下。 Ie, I want to use absolute positioning with the two child divs, but position them relative to the parent div rather than the page. 即,我想对两个子div使用绝对定位,但是相对于父div而不是页面定位它们。 How can I do this? 我怎样才能做到这一点?

Sample html: 范例html:

<div id="father">
   <div id="son1"></div>
   <div id="son2"></div>
</div>

#1楼

参考:https://stackoom.com/question/i0Ds/绝对位置-但相对于父位置


#2楼

div#father {
    position: relative;
}
div#son1 {
    position: absolute;
    /* put your coords here */
}
div#son2 {
    position: absolute;
    /* put your coords here */
}

#3楼

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top , right , bottom , left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative ." 之所以如此,是因为position: absolute是指“使用toprightbottomleft相对于最近的具有position: absoluteposition: relative祖先进行定位的东西。

So we make #father have position: relative , and the children have position: absolute , then use top and bottom to position the children. 因此,我们使#father具有position: relative ,而子代具有position: absolute ,然后使用topbottom定位子代。


#4楼

If you don't give any position to parent then by default it takes static . 如果您不给父母任何职位,那么默认情况下它将采用static If you want to understand that difference refer to this example 如果您想了解这种差异,请参考此示例

Example 1:: 示例1:

http://jsfiddle.net/Cr9KB/1/ http://jsfiddle.net/Cr9KB/1/

   #mainall
{

    background-color:red;
    height:150px;
    overflow:scroll
}

Here parent class has no position so element is placed according to body. 在此,父类没有位置,因此根据正文放置元素。

Example 2:: 示例2:

http://jsfiddle.net/Cr9KB/2/ http://jsfiddle.net/Cr9KB/2/

#mainall
{
    position:relative;
    background-color:red;
    height:150px;
    overflow:scroll
}

In this example parent has relative position hence element are positioned absolute inside relative parent. 在此示例中,父级具有相对位置,因此元素绝对位于相对父级内部。


#5楼

Incase someone wants to postion a child div directly under a parent 如果有人想将孩子div直接放在父母的下面

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 100%;
}

Working demo Codepen 工作演示Codepen

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值