So far, all the examples we've seen involve adjacent opposite margins: the bottom of one element overlaps with the top of the next element.
Surprisingly, margins can collapse even in the same direction.
Here's what this looks like in code:
<style>
.parent {
margin-top: 72px;
}
.child {
margin-top: 24px;
}
</style>
<div class="parent">
<p class="child">Paragraph One</p>
</div>
You can think of this as an extension of the previous rule. The child margin is getting “absorbed” into the parent margin. The two are combining, and are subject to the same rules of margin-collapse we've seen so far (eg. the biggest one wins).
This can lead to big surprises. For example, check out this common frustration:
In this scenario, you might expect the two sections to be touching, with the margin applied inside each container:
This seems like a reasonable assumption, since the <section>
s have no margin at all! The intention seems to be to increase the space within the top of each box, to give the paragraphs a bit of breathing room.
The trouble is that 0px margin is still a collapsible margin. Each section has 0px top margin, and it gets combined with the 32px top margin on the paragraph. Since 32px is the larger of the two, it wins.
Top comments (0)