TutorialsCSSThe Box Model
CSS

The Box Model

Every HTML element is a rectangular box. The CSS box model describes the four layers of this box, from inside out: content → padding → border → margin.

.box {
  /* Content area */
  width: 300px;
  height: 150px;

  /* Padding — space between content and border (inside) */
  padding: 20px;               /* all 4 sides */
  padding: 10px 20px;          /* top/bottom | left/right */
  padding: 5px 10px 15px 20px; /* top | right | bottom | left */

  /* Border */
  border: 2px solid #333;
  border-radius: 8px;          /* rounded corners */
  border-top: 4px solid red;   /* individual sides */

  /* Margin — space outside the border (between elements) */
  margin: 16px;
  margin: 0 auto;              /* center element horizontally */

  /* Background covers content + padding area (not margin) */
  background-color: #f0f4ff;
}

/* ── CRITICAL: Always use border-box ──────────────────────
   With default (content-box):
     300px width + 20px padding*2 + 2px border*2 = 344px rendered size!
   With border-box:
     width stays exactly 300px — padding/border fit inside it */
*, *::before, *::after {
  box-sizing: border-box;
}
💡

Set box-sizing: border-box globally at the top of every stylesheet. Without it, adding padding to a 300px element makes it 340px wide — a constant source of layout bugs.

Visual summary:

┌─────────────────────── margin ──────────────────────────┐
│  ┌──────────────────── border ────────────────────────┐  │
│  │  ┌─────────────── padding ─────────────────────┐  │  │
│  │  │                                              │  │  │
│  │  │              content area                   │  │  │
│  │  │                                              │  │  │
│  │  └─────────────────────────────────────────────┘  │  │
│  └────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

Watch & Learn

A recommended video to watch alongside this chapter.

More “The Box Model” videos on YouTube