在this example ,为什么固定的#header(位于顶部)不是从页面顶部开始,而是在this example 中是吗?
唯一的区别是我将#content 的“margin”改为“padding”(分别)。
那么为什么这个微小的变化会产生巨大的影响呢?如何将固定的#header 放在页面顶部,同时仍然为#content 使用“边距”?
最佳答案
是因为collapsing margins .
If the top and bottom margins of a box are adjoining, then it is possible for margins to collapse through it. In this case, the position of the element depends on its relationship with the other elements whose margins are being collapsed.
在这种情况下,margin
可以向下推 #header
(具有 position: fixed
)除非你给它一个 top
值不是 auto
的默认值。
解决此问题的一种方法是将 overflow: hidden
添加到 #wrapper
: http://jsfiddle.net/CyaJ8/6/
之所以可行,是因为:
Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
关于CSS:在这个例子中,为什么固定元素不从页面顶部开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6145481/