DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Nesting doesn't prevent collapsing
Top
Top

Posted on

Nesting doesn't prevent collapsing

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

<style>
  p {
    margin-top: 48px;
    margin-bottom: 48px;
  }
</style>
<div>
  <p>Paragraph One</p>
</div>
<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.

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›