What is "collapsing margins"?
Collapsing margins is the effect of vertical margin values on blocks collapsing together, where instead of adding up, the largest value is taken, and the resulting spacing becomes shared.
It happens only with vertical spacing (margin-top and margin-bottom) and only for block-level elements.
When margins collapse
- Between two adjacent block elements
css
div + div {
/* margin-bottom of the first and margin-top of the second will collapse */
}- Between a parent and its first/last child element
(if the parent has no
border,padding, oroverflow) - In an empty block (if it has no content, padding, or border)
How the result is calculated
If there are two spacings:
javascript
margin-bottom: 30px
margin-top: 20pxThe result will be 30px, not 50px.
When margins do NOT collapse
- if there is a
border - if there is
padding - if
overflow: hidden | auto | scrollis set - if the element is flex or grid
The gist in one sentence
Collapsing margins is the mechanism by which the vertical margins of two blocks merge into one, equal to the larger of the two.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.