Margin Collapse
Overview
Margin Collapse is one of the most notoriously confusing behaviors in CSS. When two block-level elements are stacked vertically, their top and bottom margins do NOT add together. Instead, they 'collapse' into each other, and the browser only uses the larger of the two values. Even weirder, a parent element's top margin can collapse with its first child's top margin, ripping the parent downward. Understanding how to control and prevent this is a rite of passage for frontend developers.
Syntax
/* HTML: <div class="box-a"></div> <div class="box-b"></div> */
.box-a {
margin-bottom: 40px;
}
.box-b {
margin-top: 30px;
}
/*
Result: The gap between them is NOT 70px!
It is exactly 40px, because the 30px margin collapses inside the 40px one.
*/Common Pitfalls
- Assuming left and right margins collapse. They absolutely do not. Margin collapse ONLY applies to the vertical axis (Top and Bottom) of block-level elements in normal document flow.
- Wondering why a parent
<div>gets pulled down the screen by its child'smargin-top. If the parent has no padding or border, the child's top margin literally 'leaks' out of the parent and pushes the parent down.
Interview Questions
By changing the parent container's layout model to display: flex; or display: grid;. Elements inside Flexbox or Grid completely ignore margin collapse, and their margins will mathematically add together as expected.
Real-World Example
A classic hack to prevent a child's margin from leaking out of its parent container.
.parent {
/* Adding even 1px of invisible padding or border creates a 'wall'
that stops the child's margin from collapsing outwards! */
padding-top: 1px;
background: lightgray;
}
.child {
margin-top: 50px; /* Now safely contained inside the parent */
}Check Your Knowledge
Test your understanding of Margin Collapse with these quick questions.