Blog Post

Collapsing a Zombie in the Face

One weird thing about vertical margins in CSS is margin collapse. It’s when two (but sometimes more) margins combine into a single margin that’s only as tall as the tallest margin. It happens most often when you have two adjacent elements. If the top and bottom margins are set to 2em on both the first element and the second element, the distance between them will not be 4em, but 2em because the margins collapsed. This can also happen if both an element and its first child have margins set. For instance if you have a div with a top margin of 2em and an h3 as its first child with a margin of 1em, you’ll have a 2em total top margin. The h3’s margin will collapse into its parent’s margin.

There are a few other cases where this may happen too, but they are less common. Check out this Mozilla Developer Network article for more details: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing