Lesson 13 of 27
The box model
Here's the single most important concept in CSS layout: every element is a box. A heading, a paragraph, an image, a div — the browser treats each as a rectangular box, and every box has the same four layers. Understand the box model and CSS layout stops being mysterious.
The four layers of every box
From the inside out, every element's box has:
- Content — the actual text or image.
- Padding — space inside the box, between the content and the border.
- Border — a line around the padding.
- Margin — space outside the box, between this box and its neighbours.
Look at the boxes: the background fills the content and the padding (so padding is coloured), the border wraps that, and the margin is the transparent gap outside — which is why the two boxes don't touch. These four layers are on every element.
Padding vs margin — the key distinction
The most important thing to get straight: padding is space inside the box; margin is space outside it.
- Padding pushes the content away from the border — it makes a box roomier inside. It's part of the box (and coloured by the background).
- Margin pushes other boxes away — it creates gaps between elements. It's outside the box (always transparent).
Padding gives content room within an element; margin creates space between elements. Mixing them up is the classic box-model confusion.
Why this matters
Almost all CSS spacing and layout comes down to controlling these four layers. "Make this button roomier" → padding. "Space these sections apart" → margin. "Draw a line around this" → border. Once you see every element as a box with content/padding/border/margin, you can control spacing precisely — and the whole of layout becomes manageable.
The mistake beginners make
Confusing padding and margin — using margin when they want internal roominess (padding), or padding when they want space between elements (margin). Ask: inside the box (padding) or outside it (margin)? Also, not realising the background fills the padding but not the margin, which explains a lot of "why is there a coloured gap / transparent gap" confusion.
Your turn
Your turn
- Add padding, border, and margin to a box and identify each layer visually.
- Compare a box with padding to one without — see how padding gives content room inside.
- Use margin to create space between two boxes. Ask each time: inside (padding) or outside (margin)?
Key points
- Every element is a box with four layers: content, padding, border, margin.
- Padding is space INSIDE the box (content to border); margin is space OUTSIDE (between boxes).
- The background fills the content and padding, but not the margin (always transparent).
- Almost all spacing and layout is controlling these four layers — inside vs outside is the key question.
Q&A · 0
Enrol to ask questions and join the discussion.
No questions yet — be the first to ask.