我正在尝试使用 http://ryanfait.com/sticky-footer/ 中的以下粘性页脚解决方案
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -4em;
}
.footer, .push {
height: 4em;
}
h1 {
margin-top:1em;
}
<html>
<head>
<link rel="stylesheet" href="layout.css" ... />
</head>
<body>
<div class="wrapper">
<h1>This header screws with sticky footer</h1>
<p>Your website content here.</p>
<div class="push"></div>
</div>
<div class="footer">
<p>Copyright (c) 2008</p>
</div>
</body>
</html>
但是,正如上面的代码片段所示,向
标记添加边距会导致出现不需要的滚动条。
根据我的基本理解,边距应该只影响
标签的大小,它不应该影响包装器的大小/位置(除非没有空间 - 但显然有足够的空间)。
编辑:我不是想找到解决方案,我想了解会发生什么。看起来 margin 并没有将
标签相对于父容器向下推,而是将父容器与 标签一起向下推。这是正确的吗?如果是,为什么?这似乎相当违反直觉。
最佳答案
如果你想操纵边距/填充属性,它总是保存添加 display:inline-block
属性而不是使用内联元素。将它添加到您的 h1
标记中,您的问题就会得到解决。
这是一篇关于这个问题的解释的帖子 Inline elements and padding
编辑:我有一个解释给你。
在 CSS 中我们有类似“折叠边距”的东西。 W3C 是这样定义它的:
In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding, or border areas, or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.
只有在以下情况下边距才相邻:
- both belong to in-flow block-level boxes that participate in the same block formatting context
- no line boxes, no clearance, no padding and no border separate them (Note that certain zero-height line boxes are ignored for this purpose.)
- both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
- top margin of a box and top margin of its first in-flow child bottom margin of box and top margin of its next in-flow following sibling
- bottom margin of a last in-flow child and bottom margin of its parent if the parent has 'auto' computed height
- top and bottom margins of a box that does not establish a new block formatting context and that has zero computed 'min-height', zero or 'auto' computed 'height', and no in-flow children
如果您想阅读更多相关信息,这里有一些有用的链接:
- > W3C.org
- > Understand CSS Margins Collapsing (清晰的解释+例子)
总而言之,有许多不同的方法可以解决这个问题。例如,将 display:inline-block
、 float:left
甚至 border:1px black
属性添加到您的包装元素或 h1
标签将解决“问题”。当然这不是真正的问题,在某些情况下折叠边距确实很有用。
关于html - 盒子模型 - 为什么带粘性页脚的页眉螺钉的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054659/