Skip to content
FORGENO ADS GAMESUnlock all $8

CSS · Unit 2: The box model · Lesson 1 of 5

Padding, border and margin

Every element is a box.

Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.

The idea

Every element is a box. From the inside out: the content, then padding (space inside the border), then the border, then margin (space outside, which pushes other boxes away).

Shorthand sets several sides at once. padding: 12px; sets all four. padding: 8px 16px; sets top and bottom to 8px and left and right to 16px.

A border needs a width, a style and a color: border: 2px solid teal. Without a style word like solid, dashed or dotted, no border appears.

Worked example

CSS

.note {
  padding: 12px 16px;
  border: 2px solid teal;
  margin: 0 0 16px;
}

The HTML it styles

<div class="note">Remember your ticket.</div>
<div class="note">Doors open at 7.</div>

Key terms

Box model
Every element is a box: content, padding, border and margin, from the inside out.
Padding
Space inside the border, between it and the content.
Border
A line around the box. It needs a width, a style and a color: 2px solid teal.
Margin
Space outside the border. margin: 0 auto centers a block with a width.

Practise it in Code Academy

It has 4 exercises (multiple choice, fix the broken code and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.

Every lesson is free: no ads, no lives and no paywall.