The box model
Every element on a web page is a rectangular box. Understanding how a box's size is calculated is the single most important concept for CSS layout.
The four layers
┌──────────────── margin ────────────────┐
│ ┌───────────── border ─────────────┐ │
│ │ ┌────────── padding ─────────┐ │ │
│ │ │ │ │ │
│ │ │ content │ │ │
│ │ │ │ │ │
│ │ └────────────────────────────┘ │ │
│ └──────────────────────────────────┘ │
└────────────────────────────────────────┘- Content: the text or image itself
- Padding: space inside the border (it takes the background colour)
- Border: the edge
- Margin: space outside the border, pushing other elements away (always transparent)
Pro tip: right-click any element → Inspect. The "Computed" panel shows a live box-model diagram, and you can hover over it to see each layer highlighted on the page.
box-sizing: the fix everyone uses
By default (content-box), width sets only the content width, and padding and border are added on top. In the box above, 200 + 20×2 + 6×2 = 252px wide. Surprising!
border-box makes width include the padding and border, which is far more intuitive:
Almost every project starts with this reset:
*, *::before, *::after {
box-sizing: border-box;
}Shorthand: 1, 2, 3 or 4 values
The values go clockwise from the top: Top, Right, Bottom, Left ("TRouBLe").
padding: 10px; /* all four sides */
padding: 10px 20px; /* top & bottom 10px, left & right 20px */
padding: 10px 20px 30px; /* top 10, left & right 20, bottom 30 */
padding: 10px 20px 30px 40px; /* top, right, bottom, left */
padding-top: 10px; /* a single side */
padding-inline: 20px; /* left + right (logical property) */
padding-block: 10px; /* top + bottom */Borders and rounded corners
outline and box-shadow don't take up space, so they never shift the layout.
Margin collapsing
When two vertical margins touch, they collapse into the larger one instead of adding together:
This only happens with vertical margins in normal flow. It doesn't happen inside flex or grid containers, which is one reason pros prefer gap for spacing.
Centring a block
Width, height and overflow
Prefer
max-widthoverwidth, andmin-heightoverheight. Fixed sizes break when the content or the screen changes.
Practice
Build a pricing card that is exactly 280px wide (including padding and border), has 24px of padding, a 1px light border, 16px rounded corners, a soft shadow, and is centred on the page. Add a full-width button inside with 12px vertical padding.
1.With box-sizing: border-box, width: 300px and padding: 20px, how wide is the box?
2.Which layer of the box takes the element's background colour?