Nesting doesn’t prevent collapsing – DEV Community

Alright, here is the place it begins to get bizarre. Take into account the next 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 right into a containing <div>, however the margins will nonetheless collapse!

How can this be? Effectively, it seems that many people have a false impression about how margins work.

Margin is supposed to extend the space between siblings. It’s _not _meant to extend the hole between a baby and its mum or dad’s bounding field; that is what padding is for.

Margin will all the time attempt to improve distance between siblings, even when it means transferring margin to the mum or dad ingredient! On this case, the impact is similar as if we had utilized the margin to the mum or dad <div>, not the kid <p>.

“However that may’t be!”, I can hear you saying. “I’ve used margin earlier than to extend the space between the mum or dad and the primary baby!”

There are some circumstances that have to be glad to ensure that the margin to be transferred to the mum or dad (and collapsed):

  • No different parts in-between (see earlier rule, in regards to the <br>).
  • The mum or dad ingredient does not have a peakset.
  • The mum or dad ingredient does not have any padding or border alongside the related edge.
    That final situation is basically frequent, so let us take a look at a fast instance. On this case, our nested baby cannot mix margin with the following paragraph, as a result of the mum or dad has some padding in the best way:

Image description

You may consider padding/border as a type of wall; if it sits between two margins, they cannot collapse, as a result of there is a wall in the best way. The width does not matter, both; even 1px of padding will intervene with margin collapse.

Add a Comment

Your email address will not be published. Required fields are marked *