Html 位置绝对但相对于父级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10487292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Position absolute but relative to parent
提问by BlaShadow
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?
我在另一个 div 中有两个 div,我想使用 css 将一个子 div 定位到父 div 的右上角,将另一个子 div 定位到父 div 的底部。即,我想对两个子 div 使用绝对定位,但将它们相对于父 div 而不是页面定位。我怎样才能做到这一点?
Sample html:
示例 html:
<div id="father">
<div id="son1"></div>
<div id="son2"></div>
</div>
回答by Domenic
#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
手段类似“使用top
,right
,bottom
,left
来定位自己相对于谁拥有最近的祖先position: absolute
或position: relative
”。
So we make #father
have position: relative
, and the children have position: absolute
, then use top
and bottom
to position the children.
所以我们让#father
have position: relative
,孩子 has position: absolute
,然后使用top
和bottom
来定位孩子。
回答by Brian Warshaw
div#father {
position: relative;
}
div#son1 {
position: absolute;
/* put your coords here */
}
div#son2 {
position: absolute;
/* put your coords here */
}
回答by petergus
回答by anam
If you don't give any position to parent then by default it takes static
. If you want to understand that difference refer to this example
如果你没有给父母任何位置,那么默认情况下它需要static
. 如果您想了解这种差异,请参阅此示例
Example 1::
示例 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::
#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.
在这个例子中,父元素具有相对位置,因此元素绝对定位在相对父元素内。