CSS Box Model
The CSS box model is the set of layers that forms every element box. The layers run from the content at the centre to the margin on the outside.
Add up the layers
The box sets all four layers in one rule. Its full width is 200 plus 40 of padding plus 10 of border.
.box {
width: 200px;
padding: 20px;
border: 5px solid blue;
margin: 10px;
}Same width, different totals
Both rules set a width of 200 pixels. The list adds padding, so its full width grows by 40 pixels.
.box {
width: 200px;
padding: 0;
}
ul {
width: 200px;
padding: 20px;
}Margin adds no width
The margin sits outside the box. It does not count in the width of the box itself.
.box {
width: 200px;
margin-left: 30px;
}Example
.box {
width: 220px;
background-color: lightblue;
padding: 18px;
border: 3px solid blue;
margin: 20px;
}
button {
padding: 8px 14px;
}Key points
- Content: the innermost layer, where the text and other elements sit
- Padding: the layer between the content and the border
- Border: the layer between the padding and the margin
- Margin: the outermost layer, around the border
- The width property sizes the content layer under the default model.
- The total width of a box adds the content, padding and border widths.
- The margin of one box sits between it and the next box.
In this example, the box works as a small card built from all four layers. Its content width is 220 pixels. Padding adds space inside the blue border, and its background fills that space. A margin of 20 pixels holds the card away from its neighbours. The button inside gains its own small padding.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What is the layer order of the box model, from inside to outside?