Why Do Margins Disappear?
We already know about margin collapse, but how to stop it? The secret lies in creating BFC (Block Formatting Context) — an independent formatting area.
When Margins DON'T Collapse:
If a " barrier " appears between blocks or parent and child:
- Padding or Border: Even 1px border stops collapse.
- Overflow: Value
hidden,auto, orscrollcreates BFC. - Display:
inline-block,flex,grid— collapse doesn't exist inside them.
.parent {
display: flow-root; /* Most modern way to create BFC and stop collapse */
}
Tip
If you see that top margin of a heading " pushed " the entire site background down — just add display: flow-root to heading's parent or minimal padding-top: 0.1px.
Note
BFC is like an invisible force shield. Everything inside it doesn't affect external margins and vice versa.