Basic

The box model

Every element is a rectangle with four layers: content, padding, border, and margin. Almost every spacing bug is a misunderstanding of which layer you changed. Learning the four names turns 'it moved a bit' into 'the padding grew'.

What you will see

Now 300 total, with the content squeezed in. Setting box-sizing on every element is the habit that removes the surprise.

About 1 min of reading

Try It

Measure the box surprise.

1

Set width and padding

.box { width: 300px; padding: 20px; border: 5px solid black; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The element is 350 pixels wide, not 300 - padding and border add outside the width.
2

Fix it

.box { box-sizing: border-box; width: 300px; padding: 20px; border: 5px solid black; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Now 300 total, with the content squeezed in. Setting box-sizing on every element is the habit that removes the surprise.

Data Flow

Four layers stack around content.
1 Content sits in the middle
↓
2 Padding surrounds it
↓
3 Border surrounds that
↓
4 Margin separates from neighbours
Why this works
Outline is not border

An outline draws outside the box and does not affect layout, which makes it the right tool for debugging a box without moving anything. A border changes the size, which is why it is the wrong tool for that check.

Space between elements, not inside them

When two elements need a gap, decide which one owns it. Setting it on the parent with one property is easier to maintain than setting it on each child, and it survives children being added.

Examples

Padding is inside, margin is outside

Padding pushes content away from the border and sits inside the element's background. Margin pushes the whole element away from its neighbours and has no background. That difference is why one of them shows the colour and the other does not.

Width is the content box

A width of 300 pixels plus padding of 20 gives a total of 340 by default, because padding adds outside the width. That surprise is the box model, and setting the box to include padding is the standard fix.

Margins collapse

Two vertical margins next to each other do not add up; the larger one wins. That collapsing explains why a gap is smaller than you set, and it only happens vertically, which is why horizontal spacing behaves differently.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Selecting what to style
Previous Lesson
Selecting what to style
Next Lesson
Placing things side by side
Placing things side by side →