为什么此绝对定位的元素相对于其容器未定位? [英] Why is this absolutely positioned element not positioning relative to its container?

查看:78
本文介绍了为什么此绝对定位的元素相对于其容器未定位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的代码,可以并排放置两个 div #container 元素.在每个这些子目录中,我都想相对于其父项( div #container )定位一个子项 div #child .

 < style>.容器 {向左飘浮;右边距:10px;}.孩子 {位置:绝对;左:0.2ex;}</style>< div class ="container"> a< br/>< div class ="child"&b; b</div></div>< div class ="container"> c< br/>< div class ="child"> d</div></div> 

但是,而不是我期望的结果-'d'定位在'c'下方,但稍微向右推,而'd'定位在'b'上方,并稍微向右定位.换句话说,绝对位置是相对于页面而不是相对于其包含元素的.

  1. 为什么会这样?我对这里的绝对定位有什么误解?
  2. 如何获得预期的行为?

请参见 jsFiddle .

解决方案

绝对定位的元素相对于其包含块的边缘定位,该块被定义为不是 position:静态.

祖先元素都不是 position:static ,因此它相对于视口的初始位置.

如果确实要绝对定位

.container 元素上的 position:relative ,则为

.

也就是说,您最好改为这样做:

  .child {左边距:0.2ex;} 

I have this simple code to place two div #container elements side by side. In each of these there is a child div #child which I would like to position relative to its parent (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. In other words the absolute position has been rendered relative to the page rather than to its containing element.

  1. Why is this the case? What have I misunderstood about absolute positioning here?
  2. How can I get the behaviour I was expecting?

See this jsFiddle.

解决方案

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.

None of the ancestor elements are position: static, so it is with respect to the initial position of the viewport.

Set position: relative on the .container elements if you really want to absolutely position them.

That said, it looks like you would be better off doing this instead:

.child {
    margin-left: 0.2ex;
}

这篇关于为什么此绝对定位的元素相对于其容器未定位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆