Episode 35 of 53
The Box Model
Understand the CSS box model — content, padding, border, and margin.
The box model is the foundation of CSS layout. Every element on a page is a rectangular box made up of four layers.
The Four Layers
From inside to outside:
- Content — the actual text, image, or content
- Padding — space between the content and the border
- Border — a line around the padding
- Margin — space outside the border, between this element and others
.box {
width: 300px; /* Content width */
padding: 20px; /* Space inside */
border: 2px solid #333; /* Border */
margin: 10px; /* Space outside */
}
content-box vs border-box
By default, width and height apply to the content only. Padding and border are added on top:
/* Default: content-box */
.box {
width: 300px;
padding: 20px;
border: 2px solid;
/* Actual width: 300 + 40 + 4 = 344px! */
}
With border-box, width includes padding and border:
/* Better: border-box */
.box {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 2px solid;
/* Actual width: 300px (padding and border are inside) */
}
The Universal box-sizing Reset
*, *::before, *::after {
box-sizing: border-box;
}
This is considered a best practice in every modern project.