Spacing and Margin Collapse

Shorthand. padding: 1rem applies to all four sides. padding: 1rem 2rem is vertical then horizontal. padding: 1rem 2rem 3rem 4rem goes clockwise from the top: top, right, bottom, left. The same pattern works for margin and border-width.

Margin collapse, the behavior that confuses everyone once. When two vertical margins meet, they do not add together. The larger one wins and the smaller disappears.

A paragraph with margin-bottom: 2rem above one with margin-top: 1rem produces a 2rem gap, not 3rem. This only happens vertically, only between block elements, and never with padding.

LIVE PREVIEW
loading editor…

Your turn → Change .b to use padding-top: 1rem instead of margin-top. The gap grows, because padding never collapses. That is the usual workaround.

✦ Pick one direction and stay consistent

Because vertical margins collapse, mixing margin-top and margin-bottom across a stylesheet produces spacing that is hard to predict. A common discipline is to only ever apply margin-bottom, so every element pushes the next one down and nothing fights.

◈ Graded Build

Build a card with predictable sizing. Apply border-box sizing to everything, then give a card class a width of 320px, padding of 1.5rem, a 2px solid border, and 2rem of space below it. With border-box the rendered width must be exactly 320px.

Checked against the page you actually render, not against how you wrote it. 3 visible and 2 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back