Andrew's Digital Garden

Margin collapse

In [[css]], adjacent margins can sometimes overlap due to something called 'margin collapse'. The rules around it are a little confusing, and often means developers opt into using something more consistent such as padding.

However it is a feature that can be tamed, and knowing how to use it sometimes comes in handy. For example, Capsize applies negative margins in combination with display: table to pseudo elements to avoid margin collapse.

Some hard and fast rules:

  • Only vertical margins can collapse
  • Only adjacent elements collapse - elements between will prevent it, even if empty
  • The resulting margin collapse value will always be the bigger margin
  • Margins can collapse, even if the elements are nested
  • Margins can collapse in the same direction. Similarly, more than two margins can collapse
  • Margins don't collapse in all [[20220815043921-layout-modes-css]], e.g. [[cssgrid]] and [[flexbox]].
  • If an element has a top and bottom margin but is empty, the margins applied to that element will collapse.

https://www.joshwcomeau.com/css/rules-of-margin-collapse/ https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

[[css]] [[layout]] [[web]]

Margin collapse