第一个 child 的上边距和最后一个 child 的下边距

Top margin of first child and bottom margin of last child

HTML

<div class="lev1">level1</div>
<div class="lev2wrap">
<div class="lev2">level2</div>
<div class="lev2">level2</div>
<div class="lev2">level2</div>
<div class="lev2">level2</div>
</div>

CSS

.lev1{
  background:lightblue;
}
.lev2wrap{
  background:gold;
}
.lev2{
  background:#999999;
  margin:10px 0;
}

为什么 lev2 的第一个实例没有 10px 的上边距,为什么 lev2 的最后一个实例没有 [=15= 的下边距]?

相反,lev2wrap 具有顶部和底部边距,但这不是 CSS 指令。

JSFIDDLE

因为collapsing margins.

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

Margin collapsing occurs in three basic cases:

  • Adjacent siblings
  • Parent and first/last child
  • Empty blocks

要显示 lev2wrap 的边距,请为其添加 overflow: auto:

.lev2wrap {
  background: gold;
  overflow: auto;
}

jsFiddle example