The box model: padding, border, margin

Every element is a box. Control the space inside and outside it.

1. What is this?

Every HTML element is drawn as a rectangular box. From inside out: the content (your text), padding (space inside the box, around the content), border (the edge), and margin (space outside the box, separating it from neighbours). A variable here is just a named value you set; padding: 16px means 'keep 16 pixels of inner space'.

2. Why do we use it?

Cramped pages feel broken. The box model is how you create breathing room, cards, and clean separation without guessing.

3. Syntax breakdown

  • .card { padding: 16px; }

    .card selects elements with class=card. padding adds inner space on all sides.

  • .card { border: 1px solid #ddd; }

    border needs width, style, colour. solid #ddd = thin grey edge.

  • .card { margin: 12px; }

    margin pushes other elements away — outer spacing.

5. Common mistakes

  • Confusing padding (inside) with margin (outside) — use padding to make a card roomier.
  • Setting margin on everything instead of one direction, causing double gaps.
  • Forgetting that borders add to the visible size of the box.

Practice task

Increase the card padding to 24px and the outer margin to 20px. Make the border 2px solid #111.

Hint

Edit the three lines inside .card, then Run.

Try it below — tests run automatically when you press Run.

css

Live preview (sandboxed)

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. What is padding?

  2. 2. What is margin?

  3. 3. Which rule adds a thin grey edge?

4. Example — edit and run

css

Live preview (sandboxed)

Output

Press Run to see output.