为什么绝对/相对位置的边距表现相同
我看到顶部/左侧属性显示绝对位置和相对位置的差异,因为它应该。
当我在position:relative上设置margin-top时,它根据包含的容器正确定位。但是当我在position:absolute上设置margin-top时,我认为它应该根据BODY元素定位,但它的位置与position:relative相同,相对于包含元素(#container)。而且我也没有将任何元素设置为非静态。
这是带有位置的代码:相对 http://jsfiddle.net/uFta4/
这里是position:absolute http://jsfiddle.net/uFta4/2/
请注意,#firstDiv 位于同一位置这是相对于#container 的。
它应该与 BODY 元素相关吗?
I see top/left properties display difference with position absolute and position relative as it should.
When I set margin-top on position:relative it positions correctly according to containing container. BUT when I set margin-top on position:absolute, I think it should be positioned according to BODY element but it is positioned same as position:relative which is relative to containing element (#container). And I have not set any element non-static as well.
Here is code with position:relative
http://jsfiddle.net/uFta4/
And here is with position:absolute
http://jsfiddle.net/uFta4/2/
Please note that #firstDiv is positioned at same location which is relative to #container.
Should it be relative to BODY element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为 RP 和 AP 元素之间存在某种意义上的差异,RP 元素会“折叠”其边距,而 AP 元素不会折叠其边距。这就是为什么您会在同一位置看到 AP 元素,因为它还计算您在其标签中给出的 BODY 边距。
为了让您更好地理解,我添加了一些代码。
查看以下变化并观察 RP 和 AP 元素的不同行为边际崩溃。
RP
我希望您现在已经清楚了。
Its because there is difference between RP and AP elements in a sense that RP elements 'collapse' their margins while AP element doesn't collapse their margin. That's why you are seeing AP element at same position because its also counting BODY margin you gave in its tag.
To make you understand better I have put couple of codes.
Look at following variations and observe different behavior margin collapsing of RP and AP elements.
RP
I hope now it will be clear to you.
position:absolute
和position:relative
的边距应该表现相同。在第一个示例中,相对定位的元素没有设置位置值,因此没有效果。
在第二个示例中,绝对定位的元素也没有设置位置值,因此它位于主体的左上角。距顶部 60 像素,主体上有 20 像素的边距,元素本身有 40 像素的边距。
并且,引用规范 ...
Margins are supposed to behave the same for
position:absolute
andposition:relative
.In your first example, the relatively positioned element doesn't have position values set, so there's no effect.
In your second example, the absolutely positioned element doesn't have position values set, either, so it's at the top left corner of the body. That's 60px from the top to account for a 20px margin on the body and a 40px margin on the element itself.
And, to quote from the specification ...