Every Element is a Box
CSS treats every HTML element as a rectangular box, made up of four layers: the content, padding, border, and margin — from innermost to outermost.
Box Model Layers
| Layer | Description |
|---|---|
| Content | The actual text, image, or other content |
| Padding | Transparent space between the content and the border |
| Border | A line that wraps the padding and content |
| Margin | Transparent space outside the border, separating it from other elements |
Visualizing the Box Model
<style>
.box {
width: 200px;
padding: 20px;
border: 4px solid steelblue;
margin: 20px;
background: #eef4fb;
}
</style>
<div class="box">Content area</div>Calculating Total Size
By default, an element’s total rendered width is width + padding-left + padding-right + border-left + border-right (margin is separate space outside the box, not part of its size).
Default Size Calculation
.box {
width: 200px;
padding: 20px;
border: 4px solid black;
}
/* Rendered width = 200 + 20 + 20 + 4 + 4 = 248px */box-sizing: border-box
The box-sizing property changes this calculation. With border-box, the width you set already includes padding and border, making sizing far more predictable.
border-box in Action
<style>
* {
box-sizing: border-box;
}
.box {
width: 200px;
padding: 20px;
border: 4px solid tomato;
background: #fdeceb;
}
</style>
<div class="box">Now width stays exactly 200px total.</div>Default box-sizing Surprises
The default box-sizing value is content-box, which is why adding padding to a fixed-width element often unexpectedly makes it wider than intended.
Best Practice
Apply box-sizing: border-box to every element with a universal selector at the top of your stylesheet. It’s one of the most common resets in real-world CSS.