3

我一直在运行一些测试来找出为什么一些 CSS 边距折叠以及为什么有些不折叠。我有以下测试代码:

<div id="seconddiv" style="margin-top:10px; margin-bottom:10px;">
    <p style="height:200px; margin-top:5px; margin-bottom:5px;">This is the first paragraph in  the second div!This paragraph is 200px tall.</p>
    <p style="height:300px; margin-top:5px; margin-bottom:5px;">This is the second paragraph in the second div!This paragraph is 300 px tall.</p>
    <p style="height:400px; margin-top:5px; margin-bottom:5px;">This is the third paragraph in the second div!This paragraph is 400px tall.</p>
</div>

我正在尝试准确获取 div 的高度,但 scrollHeight 返回“910px”。这是为什么?我期望“900px”作为scrollHeight,因为它不包括边距。

是否有一些<p>边距塌陷并计入高度?为什么有些而不是其他。我尝试了许多不同的边距高度组合,但没有值显示发生了什么。

4

3 回答 3

9

我认为您不理解“margin-collapse”的含义。

我将在以下示例中使用这个简化的标记:

HTML:

<div>
   <span>A</span>
   <span>B</span>
   <span>C</span>
</div>

CSS:

span {
    display: block;
    height: 100px;
    margin: 5px 0;
}

不是将每个边距显示为单独的间距,元素上的顶部和底部边距将与它们的兄弟元素(或者如果不存在上一个/下一个兄弟元素,则它们的父元素*)合并,以便它们之间的间距是最大的边距。

如果没有边距折叠,上述标记将显示为:

+div-----+
| margin |
|+span--+|
||A     ||
|+------+|
| margin |
| margin |
|+span--+|
||B     ||
|+------+|
| margin |
| margin |
|+span--+|
||C     ||
|+------+|
| margin |
+--------+

使用margin-collapse,标记显示为:

  margin
+div-----+
|+span--+|
||A     ||
|+------+|
| margin |
|+span--+|
||B     ||
|+------+|
| margin |
|+span--+|
||C     ||
|+------+|
+--------+
  margin

这对于 div 的高度意味着它包括每个元素的高度和它们之间的边距。

在我的示例中,高度为100 + 5 + 100 + 5 + 100 = 310.

在您的示例中,高度为200 + 5 + 300 + 5 + 400 = 910.


* 有一些额外的复杂性涉及填充、定位和浮动,由规范描述

于 2012-09-18T17:09:12.173 回答
1

边距被添加到盒子模型中,因此在您的情况下高度为 elem 高度 + 边距。然而,当相邻的元素有边距时,边距会崩溃,最大的胜利与添加的两个。在这里解释它的好文章 http://www.960development.com/understand-css-margins-collapsing/

于 2012-09-18T17:04:40.917 回答
0

scrollHeight返回

对象内容的上下边缘之间的距离

即使您的示例中的每个边距都崩溃了,第二个p边距仍然有上下 5px 的边距,这会计入其边缘之间的总距离。

那就是 900 像素 + 5 像素 + 5 像素 = 910 像素。

为了使其更简单,请检查此示例

<div id="seconddiv" style="margin-top:10px; margin-bottom:10px;">

    <!--
    Top edge is first p's top position (without top margin)
    -->

    <p style="height:100px; margin-top:5px; margin-bottom:5px;">
    First p adds 105px (100px height + 5px bottom margin collapsed) = 105px
    </p>
    <p style="height:100px; margin-top:5px; margin-bottom:5px;">
    Second p adds 105px (100px height + 5px bottom margin collapsed) = 210px
    </p>
    <p style="height:100px; margin-top:5px; margin-bottom:5px;">
    Third p adds 105px (100px height + 5px bottom margin collapsed) = 315px
    </p>
    <p style="height:100px; margin-top:5px; margin-bottom:5px;">
    Last p adds 100px (100px height) = 415px
    </p>

    <!--
    We're at the bottom edge. Margins are excluded, the total height is 415px
    -->

</div>​
于 2012-09-18T17:22:04.653 回答