CSS boxes and spacing
You'll learn how every element is a box with padding, a border and margin around its content.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You set a card to width: 300px. You add some padding so the text is not squashed. Now the card is wider
than 300 and it breaks your layout. Where did the extra come from?
Think of a framed photo on a wall. The photo is the content. The white card around the photo inside the frame is the padding. The frame is the border. The gap between this frame and the next one on the wall is the margin.
Every element on a page is a box with these four layers, from inside to outside:
- content: the text or image.
- padding: space inside the border. It takes the box's background colour.
- border: a line around the padding.
- margin: space outside the border. It is always see-through.
.card {width: 300px;padding: 20px;border: 2px solid #dddddd;margin: 16px;}
By default, width is only the content. The browser adds padding and border on both sides:
300 + 20 + 20 + 2 + 2 = 344px. That surprise is the common mistake. People set a width, add padding,
and their boxes no longer fit side by side.
The fix is one line that most developers put at the top of every CSS file:
* { box-sizing: border-box; }
Now width means the whole box, border included. The card stays 300px and the content gets smaller to
make room for the padding.
When you read CSS, look for padding, border and margin together, and check whether border-box is
set. One number like padding: 20px means all four sides. Two numbers like padding: 10px 20px mean top
and bottom first, then left and right.
Code tour
Click a line number with a ring to read the note for that line.
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3From inside to outside, what is the order of the layers?
- 2 / 3With no
box-sizingset, how wide iswidth: 100px; padding: 10px; border: 1px solid;? - 3 / 3After
box-sizing: border-box, how wide is that same box?