DEV Community 👩‍💻👨‍💻

Cover image for More than two margins can collapse

Posted on

More than two margins can collapse

Margin collapse isn't limited to just two margins! In this example, 4 separate margins occupy the same space:

Image description

It's hard to see what's going on, but this is essentially a combination of the previous rules:

  • Siblings can combine adjacent margins (if the first element has margin-bottom, and the second one has margin-top)
  • A parent and child can combine margins in the same direction Each sibling has a child that contributes a same-direction margin.

Here it is, in code. Use the devtools to view each margin in isolation:

The space between our <header> and <section> has 4 separate margins competing to occupy that space!

The header wants space below itself
The h1 in the header has bottom margin, which collapses with its parent
The section below the header wants space above itself
The p in the section has top margin, which collapses with its parent
Ultimately, the paragraph has the largest cumulative margin, so it wins, and 40px separates the header and section.

Top comments (0)

What image format should you use in your next project? 🤔