The Quirky Behavior of Margin Collapsing

Margin collapsing is one of those CSS concepts that seems straightforward at first—but the more you work with it, the more surprising edge cases you encounter. Josh Comeau’s deep dive into the subject highlights just how many unusual scenarios can trip up even seasoned developers.

At its core, margin collapsing follows a few simple rules:

  • It only happens in the block direction, regardless of writing-mode or the use of logical properties.
  • The largest margin wins when two neighboring margins collapse.
  • Adding any element between them—even a small amount of padding or border—stops the collapsing from happening.

But the behavior gets considerably stranger once you move past the basics:

  • Margins can collapse even when the elements aren’t siblings.
  • Margins in the same direction from different elements can collapse with each other.
  • The collapse can involve margins from an arbitrary number of elements at once.
  • Negative margins participate too, but it’s the most negative value that wins.
  • When multiple elements with mixed margin values are involved, there’s essentially an algorithm you need to understand to predict the outcome.

These quirks are a known pain point. The CSS Working Group itself has acknowledged the issue, describing the automatic collapsing of a single box’s top and bottom margins as the “root of all margin-collapsing evil.” It’s the kind of behavior that has to be taught explicitly rather than feeling intuitive, and it can confuse developers at any experience level.

One Unexpected Benefit of Grid Centering

Interestingly, a common technique from the past year may sidestep this messiness entirely: centering content with CSS grid by placing all elements into the middle column of a three-column grid, like .grid-wrapper > * { grid-column: 2; }. The advantage of that approach is that you still retain access to the full grid, making it easy to let specific elements stretch full-bleed or edge-to-edge when needed.

But there’s a side effect: once elements become grid items, they leave the normal flow, and margin collapsing no longer applies to them. That might have once seemed like a drawback, especially if you were used to expecting collapsing behavior. In light of how unpredictable margin collapsing can be, however, avoiding it altogether could be viewed as another benefit of the grid-based approach.