Fix the bug: the margin that escapes
Two positive vertical margins that meet do not add up. They collapse: the
two become one, and the bigger one wins. A margin-bottom: 16px resting on a
margin-top: 24px gives you a 24px gap, not 40.
The same rule fires between a parent and its first child, and that is where
it bites. If nothing sits between the parent's top edge and the child's top
margin - no border, no padding, not one pixel - then the two are touching, so
they collapse into a single margin on the parent. The child's margin-top
stops being the child's. It moves the parent instead.
That reads as two bugs at once. The gap turns up on the wrong side of the
parent's background, and the parent's box never grows, because a margin it does
not contain cannot make it taller. CSS has no complaint to make about any of
it - you just get a box with its text jammed against its own top edge.
The note below should have 24px of yellow above its title. Look at the preview:
the yellow starts at the text, and the 24px is out on the grey instead, where it
swallowed the h1's 16px as it went past.
Your task: make the note contain that 24px, so the yellow box grows to hold
it. Leave .note h2 { margin: 24px 0 0 0; } exactly as it is - the title's
margin is right, so the fix belongs on .note.
You'll practice:
- Reading a gap that landed outside a box as a collapsed margin
- Giving a parent something that keeps its child's margin inside
Related reading: Margin Collapse →