What is margin collapsing in CSS
Margin collapsing is a CSS feature where vertical margins of adjacent blocks collapse (i.e., they don't add up, but the larger one is taken).
This feature only works with vertical margins (margin-top, margin-bottom) and can cause unexpected visual effects.
Example of Margin Collapsing
<div class="block1">...</div>
<div class="block2">...</div>.block1 {
margin-bottom: 30px;
}
.block2 {
margin-top: 50px;
}What will be displayed between blocks?
50px, not 80px. Because margins collapsed (the larger one was taken).
When Does Collapsing Occur?
-
Adjacent vertically standing blocks
-
When
margin-bottomof one element bordersmargin-topof another. -
Only works vertically.
-
Parent and first/last child
-
If parent has no
padding,border,inline content, etc. -
Margin of first/last child collapses with parent's
margin. -
Empty blocks
-
If block is empty, top and bottom margins collapse into one.
How to Prevent Collapsing?
- Add
paddingorborderto parent - Use
overflow: hiddenoroverflow: auto - Use Flexbox or Grid (they don't collapse margins)
- Add
display: flow-rootto parent
Important:
Margin collapsing only works vertically and only for block elements in normal flow.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.