Here’s a one-sentence blog post about margin collapsing: When two block elements are stacked on top of one another, the vertical space between them is the larger between the one on top’s
margin-bottom and the one on the bottom’s
It’s a bit weird and ascii-shruggy. Couple caveats with them, as you might expect.
I find it fascinating how it makes for the perfect sort of mini blog post when people have an ah-ha moment about it. MDN even sees fit to have a dedicated page.
Although the margin collapse behavior is at first a little unintuitive, it does make life easier in the case of multiple nested elements, where the behavior is often desirable.
It’s probably not the most intuitive aspect of CSS, but the takeaway here is that there is some logic at play and, once you have learned it, the mystery and confusion suddenly disappears!
Do you see how collapsing margins can make things tricky? I personally encounter this on a frustratingly frequent basis when dealing with typography.
Margin collapsing can be frustrating to deal with, but knowing when and how it happens will make it easier for you to fix problems when they occur.
Collapsible margins can be a pain if you don’t properly understand when they occur. The first step to dealing with or avoiding them is [to] understand exactly which case of collapsible margins we are dealing with.
Margin collapse is something that mentioned in every CSS book’s first or second chapter. When I learned about the stylesheets in a long time ago, of course, I read about it.
The concept of margin collapse is foundational to an understanding of the box model in CSS, but it is actually quite complex and potentially confusing. The spec describing how margin collapse works is thorough but difficult to understand.
I don’t point all these out to say it’s an over-blogged subject (nothing is), but that it’s an interesting thread to follow. When so many people feel the need to explain something ultimately so small, there is something weird (probably bad) happening there.
No doubt this is why it’s considered one of the mistakes in the design of CSS:
The top and bottom margins of a box should never have been allowed to collapse together automatically as this is the root of all margin-collapsing evil.
Emphasis theirs and is, in fact, the only bold text in the entire list.
If you’re looking to stop the behavior, you’ll need to do something that probably has more side effects than it’s worth, like float the elements. It’s not quite as simple as kicking off a new Block Formatting Context, as that’s what
display: flow-root; does and that doesn’t work.
You’re probably better off just knowing about it and dealing with it as it comes up by systematically flowing margins in one direction, or getting weird.
The post Good ol’ Margin Collapsing appeared first on CSS-Tricks.