The Box Model
Every element on a page is rendered as a rectangular box, and every box is built from the same four layers, from the inside out.
.card {
width: 300px;
padding: 16px; /* space between content and border */
border: 2px solid #333; /* the border itself */
margin: 24px; /* space outside the border, between this box and others */
}
| Layer | What it does |
|---|---|
| Content | The actual text/images, sized by width/height. |
| Padding | Transparent space inside the border, pushes content inward. |
| Border | A visible (or invisible) line around the padding. |
| Margin | Transparent space outside the border, pushes other elements away. |
box-sizing
By default, width only sets the content width, padding and border are added on top, so a 300px-wide box with 16px padding and a 2px border actually takes up 336px. Most developers override this globally:
*, *::before, *::after {
box-sizing: border-box;
}
With border-box, width: 300px means the whole box, content, padding, and border, is 300px total, which is far more predictable when building layouts.
display: block vs. inline
- Block elements (
<div>,<p>,<h1>) take the full available width and stack vertically;width/height/marginall apply normally. - Inline elements (
<span>,<a>) only take up as much width as their content and sit in the flow of text; verticalmargin/heightare ignored. display: inline-blockgives you the best of both, flows like text but respectswidth/height/margin.
TIP
When a layout looks subtly "off" by a few pixels, the box model is the first thing to check, open devtools and look at the computed padding, border, and margin for the element in question.