位置绝对但相对于父级 [英] Position absolute but relative to parent
问题描述
我在另一个 div 中有两个 div,我想使用 css 将一个子 div 定位到父 div 的右上角,将另一个子 div 定位到父 div 的底部.即,我想对两个子 div 使用绝对定位,但将它们相对于父 div 而不是页面定位.我怎样才能做到这一点?
示例 html:
<div id="son1"></div><div id="son2"></div>
#father {位置:相对;}#son1 {位置:绝对;顶部:0;}#son2 {位置:绝对;底部:0;}
这是可行的,因为 position: absolute
的意思是使用 top
, right
, bottom
, >left
相对于具有 position: absolute
或 position:relative
的最近祖先定位自己."
所以我们让#father
有position:relative
,孩子有position:absolute
,然后使用top
和 bottom
来定位孩子.
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. Ie, I want to use absolute positioning with the two child divs, but position them relative to the parent div rather than the page. How can I do this?
Sample 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;
}
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
."
So we make #father
have position: relative
, and the children have position: absolute
, then use top
and bottom
to position the children.
这篇关于位置绝对但相对于父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!