为什么孩子的边缘不影响父母的身高?

在这样一个简单的示例中,子页边距不影响父页高度:

.parent{ background:
black;
}
.child{
background: LightBlue;
margin: 20px;
}
<div class="parent">
<div class="child">Some text...</div>
</div>

http://jsfiddle.net/k1eegxt3/

默认情况下,子边距通常不影响父元素的高度和父元素的尺寸,在父元素中很容易是 通过增加一些边际可以“推”到的东西来修正,例如 在父代上添加一个空白或边框:

.parent{ background:
black;
padding: 1px; /* PADDING ADDED */
}
.child{
background: LightBlue;
margin: 20px;
}

http://jsfiddle.net/fej3qh0z/

我想知道 为什么这样工作,而不仅仅是它是如何固定的。

有人能解释一下,理想情况下参考规范,为什么这样工作吗?

37721 次浏览

What you are looking for is called collapsing margins. One reason that margins collapse so that empty elements do not add vertical margin space and also to evenly space elements without the need of resetting their margins.

From the specification:

3. Margins

Note: Adjoining margins in block layout can collapse. See CSS2§8.3.1 Collapsing Margins for details. Also, margins adjoining a fragmentation break are sometimes truncated. See CSS Fragmentation 3 §5.2 Adjoining Margins at Breaks for details.

The first link in that quote is to this:

8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Adjoining vertical margins collapse, except:

  • Margins of the root element's box do not collapse.
  • If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.

You can add an overflow property to the parent element to fix this (either auto, hidden, or something else depending on your needs).

JSFiddle Example: http://jsfiddle.net/k1eegxt3/2/

Add display: flex; to parent element adjust the flex direction, align, and justify as you want, but the margin thing with appear as you want.