child 的边距和 parent 的边界

Margin on child and border on parent

我有一个 child div 的盒子。 child 有边距。如果我在 parent (div.box) 上设置边框,元素的高度会发生变化,如下图所示。诀窍在哪里?

.box {
  background: #0F3;
  border: 1px solid #000;
}
.box-border {
  background: #0F3;
}
.text {
  margin: 40px;
}
<div class="box">
  <div class="text">Content</div>
</div>

<div class="box-border">
  <div class="text">Content</div>
</div>

您遇到的问题称为折叠边距

Parent and first/last child
If there is no border, padding, inline content, or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
[source MDN emphasis mine]

如果你想防止没有边框的元素上的折叠边距,你可以在这里看到其他方法:How to disable margin-collapsing?

  • 浮动 parent
  • 将 parent 显示 属性 更改为 inline-block 或 position:absolute;
  • 将parent的溢出设置为hidden
  • ...

示例overflow:hidden;:

.box {
  background: #0F3;
  border: 1px solid #000;
}
.box-border {
  background: #0F3;
  overflow:hidden;
}
.text {
  margin: 40px;
}
<div class="box">
  <div class="text">Content</div>
</div>

<div class="box-border">
  <div class="text">Content</div>
</div>