Reputation: 15032
In a simple example like this one, the child margin does not affect parent height:
.parent{ background:
black;
}
.child{
background: LightBlue;
margin: 20px;
}
<div class="parent">
<div class="child">Some text...</div>
</div>
JSFiddle: http://jsfiddle.net/k1eegxt3/
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.:
.parent{ background:
black;
padding: 1px; /* PADDING ADDED */
}
.child{
background: LightBlue;
margin: 20px;
}
JSFiddle: http://jsfiddle.net/fej3qh0z/
I want to know why this works this way, not just how it is fixed.
Can someone explain, ideally with a reference to the specification, why this works this way?
Upvotes: 103
Views: 40625
Reputation: 49
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.
Upvotes: 4
Reputation: 2469
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/
Upvotes: 133