【问题标题】:Issues when HTML body element is positioned 'relative'HTML body 元素定位为“相对”时的问题
【发布时间】:2014-08-16 21:28:18
【问题描述】:
在其中一个网站上,我发现body 元素设置为position: relative,并且body 内的内容似乎向下移动了margin-top 在body 最顶部元素上设置的CSS 值。
为什么 body 设置了 CSS 'position: relative'?它是为了修复一些错误吗?我听说有一些 IE 错误,我们无法设置元素的绝对定位。
为什么“仅”正文中的第一个元素的“margin-top”会影响每个元素的位置?
Javascript 函数 'getBoundingClientRect()' 为任何元素返回错误值,因为它不考虑在最顶部元素上设置的这个 margin-top 值。
【问题讨论】:
-
您能否创建一个jsbin.com 演示,以便我们了解您的意思?另外不要忘记添加相关代码以在您的问题中重现问题。
标签:
html
css-position
margin
document-body
getboundingclientrect
【解决方案1】:
1. Why does the body have CSS 'position:relative' set? Is it intended to fix some bug? I heard that there was some IE bug where we were not able to set absolute positioning of elements.
FC:这不是为了修复错误,但可能是因为 body 元素的一个(直接)子元素有position:absolute。如果 body 没有 position:relative,则该子元素将相对于画布(浏览器内部窗口)定位,而不是相对于 body 元素。请参阅this tutorial('嵌套位置:绝对')了解全文。过去在这方面可能存在 IE 错误,但从 IE8 开始,IE 在这方面表现正常。
.
2. Why does 'margin-top' of 'only' the first element inside the body affect the position of every element?
FC:这是设计使然。垂直边距影响后续兄弟元素的位置,position:relative; top:20px 不会。再次,请参阅提到的教程以获取完整的故事。
.
3. Javascript function 'getBoundingClientRect()' returns wrong value for any element as it does not consider this margin-top value set on topmost element.
FC:这也是设计使然,但我不确定您是否正确解释了问题。您可以发布一些代码来演示它吗?我所知道的是你应该小心使用这种方法。请参阅this Dottoro page 了解全文,包括替代方案。