gotchaModeratepending
CSS margin collapse -- adjacent margins merge unexpectedly
Viewed 0 times
margin collapsevertical marginoverflowflex gapadjacent siblings
browser
Error Messages
Problem
Vertical margins between adjacent elements collapse into a single margin (the larger one wins). A parent with no padding/border has its margin collapse with its first/last child. Adding margin-top to a child moves the parent down instead.
Solution
Margin collapse only happens vertically (not horizontally), only with block elements, and only when nothing separates the margins. Prevention: (1) Add padding or border to parent. (2) Use overflow: auto/hidden on parent. (3) Use flexbox or grid (no margin collapse). (4) Use gap instead of margins for spacing between items.
Why
Margin collapse is a CSS spec feature designed for flowing text -- paragraph margins should merge, not stack. But it surprises everyone in layout contexts.
Revisions (0)
No revisions yet.