Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 13, 2022 01:32 am GMT

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>

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.


Original Link: https://dev.to/topcode007/nesting-doesnt-prevent-collapsing-5h96

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To