CSS Margin Collapse
When Margins in CSS Collapse, and When They Don't
2 minute read
- Do collapse:
- Vertical stacking
- Flow layout
- Elements adjacent in the DOM
- Nested elements
- Positive values or negative values
- Don't collapse:
- Horizontal stacking
- Flex, Grid, and Positioned layout
- Elements not adjacent in the DOM
- Nested elements inside a parent with padding or border
- Positive values and negative values
Margins in CSS overlap when placed next to each other. For example, a 12px margin next to a 12px margin will add up to 12px of space (12px + 12px = 12px), while a 12px margin and a 6px margin will add up to 12px as well (12px + 6px = 12px). This is because the largest margin is used.
There are notable exceptions to the rule, where margins don't collapse, but rather add up (instead of 12px + 12px = 12px, we get 12px + 12px = 24px)
- Vertical margins collapse, Horizontal margins don’t.
- Margins only collapse in flow layout1. This means they do not collapse in flex or grid layouts.
- Margins only collapse if the elements are next to each other. Elements such as a line break (
<br>) will cause the margins to be counted separately.
- Nested elements will collapse by default, but don't when the containing element has padding, a border, or an explicit height larger than its contents.
- Positive values collapse, negative values collapse, but positive and negative values together do not collapse – they are added together.
Flow Layout: when