CSS Basics: Make Your Pages Look Good
The Box Model
In this lesson you will
- Name the four layers of the box model
- Set padding, border and margin
- Use box-sizing border-box to control element size
Introduction
The most important idea in CSS layout is simple: every element is a rectangular box. Once you can picture the box, spacing stops being a mystery.
The four layers
From the inside out, every box has:
- Content: the text or image itself.
- Padding: space between the content and the border, inside the box.
- Border: a line around the padding.
- Margin: space outside the border, pushing other boxes away.
Think of a framed picture. The picture is the content, the mat is the padding, the frame is the border, and the gap to the next frame on the wall is the margin.
Quick quiz
Which layer is outside the border?
Shorthand for the four sides
You can set one side, or all four at once.
HTML
padding: 10px; /* all four sides */
padding: 10px 20px; /* top and bottom 10, left and right 20 */
padding: 5px 10px 15px 20px;/* top, right, bottom, left (clockwise) */
margin-bottom: 16px; /* just one side */The clockwise order is top, right, bottom, left. A handy trick: remember TRouBLe.
How big is the box?
By default, width sets only the content width. Padding and border are added on top. So a box with width: 200px, padding: 20px and a 4px border is actually 248px wide. That surprises everyone at first.
box-sizing: border-box
Setting box-sizing: border-box makes width include padding and border. Now a 200px box is exactly 200px wide.
Most developers apply it to everything:
HTML
*, *::before, *::after { box-sizing: border-box; }Quick quiz
A box has width: 200px, padding: 20px and a 4px border, with the default box-sizing. How wide is it in total?
Block and inline
- Block elements (like
div,p,h1) start on a new line and stretch to fill the width. - Inline elements (like
span,a,strong) sit within a line of text. Width and height do not apply to them, and vertical margins have little effect. display: inline-blockkeeps them in a line but lets width and height apply.
Try it yourself
Make the two boxes the same size with box-sizing: border-box, then add margin: 0 auto to centre the first one horizontally.
Summary
- Every element is a box: content, padding, border, margin.
- Padding is inside the border, margin is outside.
- With
box-sizing: border-box,widthincludes padding and border. - Block elements fill the line, inline elements flow in text.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading