The box model
Every element is a rectangle, and that rectangle is built out of four layers, from the inside out:
- 1Content ~ the text or image itself.
- 2Padding ~ space inside the border. Takes the background colour.
- 3Border ~ the line around it.
- 4Margin ~ space outside the border, pushing other elements away. Always transparent.
Padding pushes the box’s own edges outwards. Margin pushes other things away. That’s the whole distinction, and it’s the one people mix up.
The one line that fixes everything
By default, width: 250px sets the width of the content, and then padding and border get added on top ~ so a 250px box with 20px padding and a 5px border is actually 300px wide on screen. This is genuinely how CSS was designed and it has annoyed people for twenty-five years.
* {
box-sizing: border-box;
}
With this, width: 250px means the box is 250px wide, full stop. Padding and border fit inside.
Put it at the top of every stylesheet. I have never once regretted it.
Shorthand
padding: 20px is all four sides. padding: 10px 20px is top/bottom then left/right. padding: 5px 10px 15px 20px goes clockwise from the top. Same for margin and border-width.
Click to resume
Use the console below.