负底部间距的影响是什么?

3

首先,这里是HTML代码:

<div class="first">
    <div class="second">
        <div class="third">
           Hello, margin collapsing!
        </div>
    </div>
</div>

下面是CSS代码:

.first {
  background-color: red;
  padding: 20px;
}

.second {
  background-color: green;
  margin-bottom: -20px;
}

.third {
  background-color: yellow;
  margin-bottom: 20px;
}

在最终布局中,第三个 div 看起来好像没有底部边距。我知道这一定是第二个 div 底部边距为负的影响,但我不明白它是如何起作用的。你能否给出一个解释?

在块元素上,您可以使用负边距。第一个是填充的,第二个在其中,所以这里还好。在第二个中,您设置了负边距,在第三个中添加了它,因此完全不必要。检查当您将30添加到第三个时会发生什么:https://jsfiddle.net/sm4Lf591/ - vaso123
你的例子已经提到了答案 - 折叠边距。https://www.w3.org/TR/CSS21/box.html#collapsing-margins - CBroe
你应该查一下“边距折叠”。非常有启发性。 - Mr Lister
1个回答

1

内边距 - 简单来说,创建了一个在元素内部的无形边框。您可以在其中提供元素内部的空间(围绕内容)。

.first {
  background-color: red;
  padding: 20px;
}

在这里,你告诉我们,第一个内容必须距离两侧都有20像素的距离(因为你没有提供任何类似于padding-top的声明)。

Margin - 另一方面则相反,它会在元素周围创建空间。

.second {
  background-color: green;
  margin-bottom: -20px;
}

这段话的意思是第二个块在底部外面有一个空间。它被定义为负数,这意味着以下项目会浮动在您的元素中。
这篇文章很糟糕地解释了这一点: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接