DevLab
CSS

The CSS Box Model: margin, padding, border, and content

Understand how every HTML element is rendered as a rectangular box, how margin and padding differ, and how box-sizing:border-box changes layout forever.

Every Element is a Box

In CSS, every HTML element generates a rectangular box with four regions, from inside to outside: content (where text and child elements live), padding (space between content and border, has background color), border (visible or invisible line around padding), and margin (transparent space outside the border separating elements).

The Default box-sizing Trap

By default, CSS uses box-sizing: content-box. A 200px wide div with padding: 20px; border: 2px solid; actually occupies 244px total (200 + 20×2 + 2×2). This is the source of countless layout bugs.

/* The fix — apply globally at the start of every project */
*, *::before, *::after {
  box-sizing: border-box;
}

/* Now this div is exactly 200px wide total */
.card {
  width: 200px;
  padding: 20px;
  border: 2px solid #ccc;
}

Margin vs Padding

Padding is space inside the element (part of the clickable area, has background color). Margin is space outside (affects layout, transparent, collapses with adjacent margins).

  • Space between text and button edge → padding
  • Space between two buttons → margin
  • Larger clickable area → padding (margin does not extend the click target)

Margin Collapse

When two vertical margins meet, they collapse into a single margin equal to the larger of the two — not the sum. This only happens with vertical margins, not horizontal ones, and does not occur inside flex or grid containers.

/* Two paragraphs have 30px gap, not 50px (20 + 30) */
p { margin-top: 20px; margin-bottom: 30px; }

Inspecting the Box Model

Open browser DevTools, select an element, and look at the Computed tab. The visual box model diagram shows exact margin, border, padding, and content dimensions — the fastest way to debug layout issues.

More Learning Topics