我在另一个div中有两个div,我想将一个子div放在父div的右上角,另一个子div使用css放在父div的底部 . 即,我想使用两个子div的绝对定位,但相对于父div而不是页面定位它们 . 我怎样才能做到这一点?
示例html:
<div id="father"> <div id="son1"></div> <div id="son2"></div> </div>
#father { position: relative; } #son1 { position: absolute; top: 0; } #son2 { position: absolute; bottom: 0; }
这是有效的,因为 position: absolute 意味着“使用 top , right , bottom , left 来定位自己与最近的祖先 position: absolute 或 position: relative 的关系 . ”
position: absolute
top
right
bottom
left
position: relative
所以我们让 #father 有 position: relative ,孩子们有 position: absolute ,然后使用 top 和 bottom 定位孩子 .
#father
div#father { position: relative; } div#son1 { position: absolute; /* put your coords here */ } div#son2 { position: absolute; /* put your coords here */ }
如果您没有给父母任何职位,那么默认情况下需要 static . 如果您想了解这种差异,请参阅此示例
static
Example 1::
http://jsfiddle.net/Cr9KB/1/
#mainall { background-color:red; height:150px; overflow:scroll }
这里父类没有位置,因此元素根据主体放置 .
Example 2::
http://jsfiddle.net/Cr9KB/2/
#mainall { position:relative; background-color:red; height:150px; overflow:scroll }
在此示例中,父项具有相对位置,因此元素位于相对父项内的绝对位置 .
如果有人想直接在父母下面设置一个子div
#father { position: relative; } #son1 { position: absolute; top: 100%; }
工作演示Codepen
4 回答
这是有效的,因为
position: absolute
意味着“使用top
,right
,bottom
,left
来定位自己与最近的祖先position: absolute
或position: relative
的关系 . ”所以我们让
#father
有position: relative
,孩子们有position: absolute
,然后使用top
和bottom
定位孩子 .如果您没有给父母任何职位,那么默认情况下需要
static
. 如果您想了解这种差异,请参阅此示例Example 1::
http://jsfiddle.net/Cr9KB/1/
这里父类没有位置,因此元素根据主体放置 .
Example 2::
http://jsfiddle.net/Cr9KB/2/
在此示例中,父项具有相对位置,因此元素位于相对父项内的绝对位置 .
如果有人想直接在父母下面设置一个子div
工作演示Codepen