CSS Tutorial
CSS Box Model
Every element in CSS is a rectangular box made of four layers: content, padding, border and margin. Understanding this "box model" is essential for layout and spacing.
The four layers of a box
The box model describes how the space around an element is built up in layers, from the inside out.
- Content: the actual text, image or other content.
- Padding: transparent space inside the border, around the content.
- Border: a line that wraps around the padding and content.
- Margin: transparent space outside the border, separating this box from others.
Seeing the layers
In the example below, the padding (space inside), border (the line) and margin (space outside) are all visible. Change the numbers and watch the box grow and move.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.box {
width: 200px;
background-color: #dbe7ff;
padding: 20px; /* space inside */
border: 6px solid #2b5cff; /* the border */
margin: 30px; /* space outside */
}
</style>
</head>
<body>
<div class="box">Content sits inside padding, border and margin.</div>
</body>
</html>How total size is calculated
By default, the width you set applies only to the content. Padding and border are added on top, so the actual space an element takes up is larger than the width value.
/* content 200 + padding 20*2 + border 6*2 = 252px total width */
.box {
width: 200px;
padding: 20px;
border: 6px solid #2b5cff;
}The box-sizing fix
This math surprises many beginners. Setting box-sizing: border-box changes the rule so that width includes padding and border. Now width: 200px means the box is exactly 200px wide, no matter the padding. Many developers apply this to every element.
* {
box-sizing: border-box;
}Box model reference
| Layer | Space type | Colored? |
|---|---|---|
| Content | Text and images | Yes (element color) |
| Padding | Inside the border | Yes (element color) |
| Border | The wrapping line | Yes (border color) |
| Margin | Outside the border | No (transparent) |
Adding box-sizing: border-box to the universal selector (*) at the top of your CSS makes element sizes far easier to reason about. Most modern projects do this.
Key points
- Every element is a box: content, padding, border, margin.
- Padding is inside the border; margin is outside it.
- By default width covers only the content area.
- Padding and border add to the default total size.
- box-sizing: border-box makes width include padding and border.
