[英]Why is this absolutely positioned element not positioning relative to its container?
I have this simple code to place two div #container
elements side by side.我有这个简单的代码来并排放置两个
div #container
元素。 In each of these there is a child div #child
which I would like to position relative to its parent ( div #container
).在每一个中都有一个子
div #child
,我想相对于它的父级( div #container
)定位它。
<style>
.container {
float:left;
margin-right: 10px;
}
.child {
position: absolute;
left: 0.2ex;
}
</style>
<div class="container">a<br/>
<div class="child">b</div>
</div>
<div class="container">c<br/>
<div class="child">d</div>
</div>
However, rather than the result I would expect - 'd' is positioned below 'c' but pushed slightly to the right, 'd' is instead positioned over 'b' and slightly to the right.然而,不是我期望的结果 - 'd' 位于 'c' 下方但稍微向右推,'d' 而是位于 'b' 上方并稍微向右。 In other words the absolute position has been rendered relative to the page rather than to its containing element.
换句话说,绝对位置是相对于页面而不是其包含元素呈现的。
Absolutely positioned elements are positioned with respect to the edges of their containing block , which is defined as the first ancestor that is not position: static
.绝对定位的元素相对于其包含块的边缘定位,它被定义为第一个不是
position: static
祖先。
None of the ancestor elements are position: static
, so it is with respect to the initial position of the viewport.没有一个祖先元素是
position: static
,所以它是相对于视口的初始位置的。
Set position: relative
on the .container
elements if you really want to absolutely position them.如果你真的想绝对定位它们,请在
.container
元素上设置position: relative
。
That said, it looks like you would be better off doing this instead:也就是说,看起来你最好这样做:
.child {
margin-left: 0.2ex;
}
To position the child relative to its parent, just add position:relative
to the PARENT'S style - then all children with position:absolute will be absolute relative to the parent.要将子项相对于其父项
position:relative
,只需添加position:relative
到 PARENT'S 样式 - 然后所有具有 position:absolute 的子项将绝对相对于父项。
.container {
float:left;
margin-right: 10px;
position:relative;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.