Child margin doesn't affect parent height

This might be obvious for some, but I found it hard to find the solution for this.

Note for answer-ers: please jump to "The REAL question", thanks :)

But I found it - it is below description of the problem:

The problem:

In simple example like this one the child margin does not affect parent height

HTML

<div class="parent">
    <div class="child">Some text...</div>
</div>

CSS

.parent{ background: black; }
.child{
    background: LightBlue;
    margin: 20px;
}

Fiddle: http://jsfiddle.net/k1eegxt3/

The solution:

Is quite simple, by default, child margins do not affect parent height respectively parent dimensions in general, it is easily fixed by adding something that margin could "push" to in parent element, e.g. add a padding or border to parent.

Adjusted CSS:

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

Fiddle: http://jsfiddle.net/fej3qh0z/

The REAL question:

However I actually want to know why does this work this way, not just how it is fixed,
so please, could someone please write an answer explaining this behaviour and add some DOC references?

Many thanks :)


It's called Collapsing margins. Documentation from www.w3.org:

6.2. Collapsing margins

Certain adjoining margins combine to form a single margin. Those margins are said to “collapse.” Margins are adjoining if there are no nonempty content, padding or border areas or clearance to separate them.

More information with examples: http://www.w3.org/TR/css3-box/#collapsing-margins

You can add overflow: auto; to the parent element to fix this.

Fiddle: http://jsfiddle.net/k1eegxt3/2/


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