CSS:在这个例子中,为什么固定元素不从页面顶部开始?

标签 css html stylesheet

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/

相关文章:

html - 垂直对齐 float DIV

html - 未选择任何内容的 SELECT html 元素的 CSS 选择器

javascript - 使用 moovweb 转换类别下拉列表以切换

tinymce - 无法在目标节点 : loading stylesheet crashes 上初始化 TinyMCE

latex - 在 LaTeX 样式表中自动设置 pdftitle 和 pdfauthor

javascript - 在动态 html 中呈现外部、内部、内联 css 样式之间的区别

php - IE6 PNG 透明度修复用于与 rotate.php 一起使用的图像

css - 背景: transparent url(); do?是什么

css - 对齐 p :dataList components in a panelGrid

javascript - HTML/CSS/JS 中未捕获的类型错误