← Lessons

quiz vs the machine

Silver1080

Frontend

The CSS Box Model

How content, padding, border, and margin add up to a box.

4 min read · intro · beat Silver to climb

Every element is a box

In CSS every element is a rectangular box made of four layers from the inside out:

  • Content holds text or child elements.
  • Padding is space inside the border, around the content.
  • Border wraps the padding.
  • Margin is space outside the border that separates the box from neighbors.

The width trap

By default, width sets only the content width, so padding and border are added on top. A box you sized to a clean number ends up wider than expected.

The fix is box sizing set to border box. Then width includes content, padding, and border, so the box stays the size you asked for. Many projects set this globally.

Margin collapse

Vertical margins between blocks can collapse, meaning the larger of two adjacent margins wins instead of summing. This surprises people and only happens vertically, not horizontally.

Key idea

A box is content plus padding plus border plus margin, and setting box sizing to border box makes width include padding and border so sizes stay predictable.

Check yourself

Answer to earn rating on the learn ladder.

1. With the default box sizing, what does width set?

2. What does box sizing border box do?