☼
⌃
☰

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:

TEXT
┌──────────────────────────────┐
│           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.

CSS
/* 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.

TEXT
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.

TEXT
Total width = width (padding and border included)
Only margin is added outside this.

Apply globally — almost universal in modern CSS:

CSS
html {
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: inherit;
}

Common Properties

CSS
.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-box globally 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-box these add to the specified width
  • margin: 0 auto only centres block elements with an explicit width — flex/grid children use align-self / justify-self instead
  • Margin collapsing only applies vertically and only to block elements in normal flow — it does not occur inside flex or grid containers