The Box Model
Every HTML element is rendered as a rectangular box made of content, padding, border, and margin — understanding this model is the key to controlling spacing and layout.
The Four Layers
From the inside out, every box consists of its content, padding (space inside the border), border, and margin (space outside the border, between this box and its neighbours).
.card {
width: 300px;
padding: 20px;
border: 2px solid #ccc;
margin: 16px;
}
box-sizing: border-box
By default, width only sets the content area — padding and border are added on top, making the box larger than the width you specified. Setting box-sizing: border-box makes width include padding and border, which is far more predictable and is used almost universally in modern CSS.
*, *::before, *::after {
box-sizing: border-box;
}
Common Mistakes
- Forgetting that default sizing adds padding and border on top of the declared width, resulting in boxes larger than expected.
- Using margin when padding was needed (or vice versa) — margin is outside the border, padding is inside it.
- Not accounting for margin collapsing between adjacent vertical margins on block elements.
- Setting a fixed width and then adding padding without
border-box, causing layouts to overflow their container.
Professional Tip
Apply the universal box-sizing: border-box reset at the very top of every stylesheet. It removes an entire category of sizing surprises and is considered a standard best practice across the industry.
Your Turn
Build three boxes side by side with different combinations of padding, border, and margin, then toggle box-sizing between content-box and border-box to see the visual difference.
Mini Quiz
What does setting box-sizing: border-box change?
border-box, the width and height you declare include the padding and border, so the box's final rendered size matches what you specified.