CSS Box Model
Every element is a box made of four layers: content → padding → border → margin. Understanding this is the key to predictable layouts.
Watch each layer build up:
name="box-model"
The four layers
┌───────────────────────┐
│ margin │
│ ┌─────────────────┐ │
│ │ border │ │
│ │ ┌───────────┐ │ │
│ │ │ padding │ │ │
│ │ │ ┌───────┐ │ │ │
│ │ │ │content│ │ │ │
│ │ │ └───────┘ │ │ │
│ │ └───────────┘ │ │
│ └─────────────────┘ │
└───────────────────────┘
Padding vs margin
- padding — space inside the border, between it and the content
- margin — space outside the border, between elements
.card {
padding: 1rem; /* pushes content inward */
margin: 1rem; /* pushes other elements away */
}
Borders
Borders sit between padding and margin.
.card {
border: 2px solid #223422;
border-radius: 8px;
}
box-sizing
By default width sets the content width — padding and border are added on top. border-box makes width include them, which is almost always what you want.
* {
box-sizing: border-box;
}