Boxes and positioning

Margin and padding

Create internal and external spacing, use logical properties, and recognize when vertical block margins collapse.

Padding is space inside the border. Margin is space outside it. Padding makes the box roomier, margin pushes other boxes away.

.card {
  padding: 1rem 1.5rem;
  margin-block: 2rem;
}

The padding shorthand with two values sets top and bottom to the first, left and right to the second. With four values it goes clockwise: top, right, bottom, left. One value sets all four sides.

Logical properties

margin-block is new if you’ve only seen margin-top and margin-bottom. It’s a logical property: it sets the margin at the start and end of the block direction, which is vertical in English. margin-inline handles the inline direction, horizontal for us. padding-block and padding-inline work the same way.

Why not just say top and bottom? Because in a vertical writing mode, or a right-to-left language, the directions turn around. Logical properties follow the text. I’ve switched to them for spacing, and they read well: margin-inline: auto says “center this” better than two separate margins.

Margins collapse

Here’s the part that confuses everyone at first. Take two paragraphs, each with margin-block: 2rem. You’d expect 4rem between them. You get 2rem.

Vertical margins between blocks in normal flow collapse: when two of them touch, they merge into one, and the larger wins. Two 2rem margins become 2rem. A 2rem and a 3rem become 3rem.

It also happens between a parent and its first or last child. If a card has no padding and no border, and its first heading has a top margin, that margin escapes the card and pushes the whole card down. Add 1px of padding or a border and the margin stays inside, because something now separates the two boxes.

Margins don’t collapse for flex and grid items. That’s one reason those layouts feel more predictable.

Don’t paper over it

When spacing looks wrong, don’t add random padding until it looks right. Open the Layout diagram, hover the margins, and see which ones merged. Then decide who owns the space, the parent or the children. Usually the fix is moving the margin to the right element, not adding more.

Use gap inside layouts

Inside a Flexbox or Grid container, don’t space items with margins at all. Use gap on the container:

.features {
  display: flex;
  gap: 2rem;
}

The gap goes only between items. No margin on the first or last item to cancel out, no collapsing to think about. The spacing lives in one place, on the container.

Try it on the course page. Give the paragraphs inside .hero a margin-block: 2rem and measure the space between them in the Layout diagram: 2rem, not 4rem. Then wrap the three cards in a flex column with gap: 2rem and compare. Same visual gap, but now it’s one explicit value instead of two margins negotiating.

Lesson completed