为什么Chrome和Firefox在保证金方面表现不同?

Mic*_*Mic 5 css

我试图了解Chrome和Firefox之间的行为差​​异.我已经发布了以下CodePen来说明这一点.

使用Firefox时,页脚元素会粘贴到包装div的底部,这要归功于margin-top: -50px它的应用.这是我所期待的.

使用Chrome(和IE),margin-bottomp元素会向下推动页脚,使其溢出.这是为什么?

html, body {
    margin: 0px;
    height: 100%
}
header {
    background-color: dodgerblue;
    opacity: 0.5;
}
#wrapper {
    background-color: tomato;
    position: relative;
    min-height: 100%;
}
 
#container p {
    background-color: lightgreen;
    width: 500px;
    /*margin-bottom: 0px;*/
}
footer {
    height: 50px;
    background-color: dodgerblue;
    margin-top: -50px;
    opacity: 0.5;
}
Run Code Online (Sandbox Code Playgroud)
<body>
    <div id="wrapper">
        <header>.</header>
        <div id="container">
            <p>.</p>
        </div>
    </div>
    <footer></footer>
</body>
Run Code Online (Sandbox Code Playgroud)

Ori*_*iol 4

原因

那是因为p里面的元素#wrapper有一些边距,可能会崩溃。

边距崩溃简介

CSS 2.1 规范说

8.3.1 折叠边距

在 CSS 中,两个或多个框的相邻边距可以组合起来形成单个边距。据说以这种方式组合的利润会 崩溃[...]

相邻的垂直边距折叠 [...]

你的风格

你的#wrapper元素有

#wrapper {
  height: auto;
  min-height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

旧行为 (Firefox)

版本的规范

“height”为“auto”且“min-height”小于元素使用高度且“max-height”大于元素使用高度的流入块级元素的下边距 与其最后一个元素相邻如果元素没有底部填充或边框,则为流入块级子级的底部边距。

#wrapperheight: auto。但是,如果窗口比其内容高,min-height则将是使用的高度(不能小于)。因此,利润率不会崩溃。

这是在 Firefox 上观察到的行为。

新行为(Chrome)

然而,规范发生了变化,现在 的值min-height并不重要:

重新表述了相邻边距的规则,以便元素的“最小高度”和“最大高度”对元素的底部边距是否与其最后一个子元素的底部边距相邻没有影响。

新规则是

如果父级具有“自动”计算高度,则最后一个流入子级的下边距与其父级的下边距[相邻]

因此,由于heightauto,边距应该折叠。

这是在 Chrome 上观察到的行为。

笔记

当前的规范似乎暗示这min-height: 0是一个要求:

上述规则意味着“高度”为“auto”且“最小高度”为零的流入块框的底部边距与其最后一个流入块级子级的底部边距折叠[... ]

但事实并非如此。这句话将在 CSS 2.2 中得到澄清。

插图

以下动画片段min-height说明了 Chrome 和 Firefox 之间的行为差​​异:

  • min-height小于内容的高度时,
    • 使用的height是内容之一
    • Chrome 和 Firefox 上的边距都会崩溃
  • 否则,
    • 使用的heightmin-height
    • Chrome 上的边距会塌陷,但 Firefox 上不会塌陷

因此,当min-height到达内容的高度时,在 Firefox 上,由于边距塌陷而导致空间突然(消失)出现。

#wrapper {
  background: orange;
  margin: 0 1em;
  -webkit-animation: animate 1s linear infinite alternate;
  animation: animate 1s linear infinite alternate;
}
footer {
  background: red;
}
p {
  margin: 1em 0;
  height: 1.75em;
  background: green;
}
@-webkit-keyframes animate {
  from { min-height: 4em; }
  to   { min-height: 6em; }
}
@keyframes animate {
  from { min-height: 4em; }
  to   { min-height: 6em; }
}
/* Content is 4.5em tall */
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
  <p>Line 1</p>
  <p>Line 2</p>
</div>
<footer>Footer</footer>
Run Code Online (Sandbox Code Playgroud)