html - 盒子模型 - 为什么带粘性页脚的页眉螺钉的边距

标签 html footer sticky-footer css

我正在尝试使用 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

如果您想阅读更多相关信息,这里有一些有用的链接:

总而言之,有许多不同的方法可以解决这个问题。例如,将 display:inline-blockfloat:left 甚至 border:1px black 属性添加到您的包装元素或 h1 标签将解决“问题”。当然这不是真正的问题,在某些情况下折叠边距确实很有用。

关于html - 盒子模型 - 为什么带粘性页脚的页眉螺钉的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054659/

相关文章:

html - 在页脚中水平重复 x 图像

kotlin - 如何向 Kotlin Dokka 文档添加页脚?

html - 如何使 <Footer> 使用网页的 100% 宽度

html - 带有站点长容器的粘性页脚

html - 如何使用 CSS 制作带链接的页脚?

javascript - 使用直接链接触发 onClick() 事件

javascript - 我可以使用 javascript 在每隔一行插入一些字符串吗?

php - 将php变量发送到另一个php页面

css - 当使用高度百分比时,这些额外的像素来自哪里?

html - 表未根据 colgroup 中的 % 调整列的大小