How the CSS box model works
Meet the four areas
Every element has a content box surrounded by padding, border, and margin. Backgrounds extend through padding but not margin.
- Content holds text or descendants
- Padding creates inner space
- Border draws around content and padding
- Margin separates the box from neighbors
Use border-box sizing
With border-box, a declared width includes padding and border, which makes sizing predictable.
*, *::before, *::after {
box-sizing: border-box;
}
Calculate a box
Under the default content-box model, a 300px width plus 20px padding on both sides and 2px borders occupies 344px before margins.
.card {
width: 300px;
padding: 20px;
border: 2px solid;
}
Manage overflow
Content can exceed fixed dimensions. Prefer flexible sizing; when clipping or scrolling is intentional, set overflow explicitly.
.code-sample {
max-width: 100%;
overflow-x: auto;
}