为什么只有一些CSS边距崩溃?

时间:2012-09-18 16:50:55

标签: html css android-webview margins

我一直在运行一些测试,以找出为什么有些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>边距是否会崩溃并计入高度?为什么有些人而不是其他人我尝试了许多不同的边距高度组合,没有任何数据显示正在发生的事情。

3 个答案:

答案 0 :(得分:8)

我认为你并不了解“保证金崩溃”的含义。

我将在以下示例中使用this simplified markup

HTML:

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

CSS:

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

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

如果没有保证金崩溃,上述标记将显示为:

+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


*有一些额外的复杂性涉及填充,定位和浮动,这是described by the specification

答案 1 :(得分:1)

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

答案 2 :(得分:0)

scrollHeight返回

  

the distance between the top and bottom edges of the object's content

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

那是900px + 5px + 5px = 910px。

为简化起见,check this example

<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>​
相关问题