CSS Box Model
Table of Contents
Related: Cascading Style Sheets
Every HTML element is rendered as a rectangular box composed of four concentric layers. Understanding the box model is the foundation of controlling spacing, sizing, and layout in CSS.
The Four Layers
From innermost to outermost:
┌──────────────────────────────┐ │ margin │ │ ┌────────────────────────┐ │ │ │ border │ │ │ │ ┌──────────────────┐ │ │ │ │ │ padding │ │ │ │ │ │ ┌────────────┐ │ │ │ │ │ │ │ content │ │ │ │ │ │ │ └────────────┘ │ │ │ │ │ └──────────────────┘ │ │ │ └────────────────────────┘ │ └──────────────────────────────┘
| Layer | Controlled by | Background | Notes |
|---|---|---|---|
| Content | width, height |
Yes | Actual text, images, etc. |
| Padding | padding |
Yes | Space between content and border |
| Border | border |
Visible | Wraps padding and content |
| Margin | margin |
No (transparent) | Space between this and other elements |
Margin collapsing
Vertical margins between adjacent block elements collapse to whichever is larger — they do not add together. Horizontal margins never collapse.
/* Adjacent elements — gap between them is 20px, not 30px */ .top { margin-bottom: 20px; } .bottom { margin-top: 10px; }
box-sizing
Controls what width and height actually measure.
content-box (default)
width and height apply to the content area only. Adding
padding or border increases the total rendered size.
Total width = width + padding-left + padding-right + border-left + border-right
border-box (modern best practice)
width and height include content + padding + border. The
overall size stays as specified; padding and border eat into
the content area instead.
Total width = width (padding and border included) Only margin is added outside this.
Apply globally — almost universal in modern CSS:
html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; }
Common Properties
.element { /* Content */ width: 300px; height: 200px; /* Padding — shorthand: top right bottom left */ padding: 16px 24px 16px 24px; padding: 16px 24px; /* top/bottom left/right */ padding: 16px; /* all sides */ /* Border */ border: 1px solid #ccc; border-top: 2px dashed red; border-radius: 8px; /* Margin */ margin: 0 auto; /* center horizontally */ margin-top: 24px; }
Tips
- Apply
box-sizing: border-boxglobally on every project — it makes width percentages predictable regardless of padding - When an element is wider than expected, check cumulative
padding and border; with
content-boxthese add to the specifiedwidth margin: 0 autoonly centres block elements with an explicitwidth— flex/grid children usealign-self/justify-selfinstead- Margin collapsing only applies vertically and only to block elements in normal flow — it does not occur inside flex or grid containers