Content, Padding, Border, Margin

What this is. Every element is rendered as a rectangular box with four layers, working outward:

Content, the text or image itself.

Padding, space inside the box, between the content and the border. Backgrounds extend through it.

Border, the line around the padding.

Margin, space outside the box, pushing other elements away. Always transparent.

The distinction that matters. Padding is inside, so it is part of the element and takes its background color. Margin is outside, so it is empty space between this element and its neighbors. When you want breathing room within a card, that is padding. When you want space between cards, that is margin.

LIVE PREVIEW
loading editor…

The cream area is padding, still part of the element. The gap between the two boxes is margin, which shows the page background through it.

Your turn → Swap the padding and margin values. The box shrinks and the gap grows, because you have moved the space from inside to outside.

✦ box-sizing is the fix everyone eventually applies

By default, width sets the width of the CONTENT only, so padding and border are added on top. Setting width: 300px with 1rem padding gives you a box 332px wide, which makes layout math miserable. Setting box-sizing: border-box makes width mean the whole box including padding and border, which is what almost everyone actually expects.

LIVE PREVIEW
loading editor…

Your turn → Both declare width: 300px, and they render at different widths. Measure them. This is why nearly every stylesheet starts by setting border-box on everything.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Spacing and Margin Collapse →
← Back