本文翻译自: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楼
参考:/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 becauseposition: absolute
means something like "usetop
,right
,bottom
,left
to position yourself in relation to the nearest ancestor who hasposition: absolute
orposition: relative
."之所以如此,是因为position: absolute
是指“使用top
,right
,bottom
,left
相对于最近的具有position: absolute
或position: relative
祖先进行定位的东西。
So we make#father
haveposition: relative
, and the children haveposition: absolute
, then usetop
andbottom
to position the children.因此,我们使#father
具有position: relative
,而子代具有position: absolute
,然后使用top
和bottom
定位子代。
#4楼
If you don't give any position to parent then by default it takesstatic
.如果您不给父母任何职位,那么默认情况下它将采用static
。If you want to understand that difference refer to this example如果您想了解这种差异,请参考此示例
Example 1::示例1:
/Cr9KB/1//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:
/Cr9KB/2//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