An Interest In:
Web News this Week
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
- April 11, 2024
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!
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
height
set. - 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:
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To