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 (parent/child)
- A good fix for this can be
display: flow-root
- 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]].
- Margins don't collapse in a scroll container (e.g.
overflow: auto
) - Margins don't collapse if there's empty space between margins
- Margins don't collapse if there's padding/border
- 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]]