Collapsing Margins in CSS
When the margins of two adjacent elements are collapsed—or combined—into just a single margin, we call this behavior margin collapsing.
The final margin size will be equal to the largest of the two margins.
For example, if an element with a 20px margin collapses with an element with a 30px margin, the margin size you’ll end up with is just 30px.
This is something that only occurs on vertical block-level elements, and can be a source of frustration when you don’t see your margins behaving the way you expect them to.
Let’s take a look at 3 different cases where this behavior can be seen.
Adjacent siblings
If the bottom margin and top margin of two sibling elements are touching, the margins will collapse:
HTML:
<h1>The bottom margin of this heading is collapsed...</p>
<p>...with the top margin of this paragraph.</p>
CSS:
h1 {
margin-bottom: 15px;
}
p {
margin-top: 10px;
}
Result:
Parent and first/last child
If there is nothing to separate the margin between a parent and its child, such as content, padding or a border, then the margins will collapse. When this happens, the margin will end up outside of the parent element.
HTML:
<div>
<p>The margin of this paragraph ends up outside the parent.</p>
</div>
CSS:
div {
margin-top: 10px;
}
p {
margin-top: 20px;
}
Result:
Empty blocks
If there is no content, padding or border to separate a block’s top margin from its bottom margin, then the margins will collapse. However, if you give the empty block a height or min-height, it will not collapse.
HTML:
<div>Top block.</div>
<div id="empty"></div>
<div>Bottom block.</div>
CSS:
#empty {
margin-top: 50px;
margin-bottom: 50px;
}
Result:
Other cases
If there are negative margins involved, the margin size will be equal to the positive margin minus the negative margin. So if you have one element with a bottom margin of 30px and an element below with a top margin of -10px, the final margin size will be 20px.
Also note that elements outside of the normal document flow, such as floated or absolutely positioned elements, will not be affected by margin collapsing.
To avoid problems with margin collapsing, you might want to consider applying only top margin or bottom margin to elements, as a good practice.
Margin collapsing can be frustrating to deal with, but knowing when and how it happens will make it easier for you to fix problems when they occur.