DEV Community 👩‍💻👨‍💻

Cover image for Nesting doesn't prevent collapsing

Posted on

Nesting doesn't prevent collapsing

Alright, here's where it starts to get weird. Consider the following code:

  p {
    margin-top: 48px;
    margin-bottom: 48px;
  <p>Paragraph One</p>
<p>Paragraph Two</p>
Enter fullscreen mode Exit fullscreen mode

We're dropping our first paragraph into a containing <div>, but the margins will still collapse!

Image description

How can this be? Well, it turns out that many of us have a misconception about how margins work.

Margin is meant to increase the distance between siblings. It is _not _meant to increase the gap between a child and its parent's bounding box; that's what padding is for.

Margin will always try and increase distance between siblings, even if it means transferring margin to the parent element! In this case, the effect is the same as if we had applied the margin to the parent <div>, not the child <p>.

“But that can't be!”, I can hear you saying. “I've used margin before to increase the distance between the parent and the first child!”

There are some conditions that must be satisfied in order for the margin to be transferred to the parent (and collapsed):

  • No other elements in-between (see earlier rule, about the <br>).
  • The parent element doesn't have a heightset.
  • The parent element doesn't have any padding or border along the relevant edge. That last condition is really common, so let's look at a quick example. In this case, our nested child can't combine margin with the next paragraph, because the parent has some padding in the way:

Image description

You can think of padding/border as a sort of wall; if it sits between two margins, they can't collapse, because there's a wall in the way. The width doesn't matter, either; even 1px of padding will interfere with margin collapse.

Latest comments (0)

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.