← Back to all tutorials

Box Model Review

Review the CSS Box Model — content, padding, border, and margin — and how it affects element sizing.

Box Model Review

Before we dive into positioning, we need to understand the CSS Box Model — because every element on the page is a box, and positioning is all about placing those boxes.

The Four Layers

Every HTML element is wrapped in a box made up of four layers:

┌─────────────── Margin ──────────────┐
│  ┌─────────── Border ──────────┐    │
│  │  ┌─────── Padding ──────┐   │    │
│  │  │                      │   │    │
│  │  │      Content         │   │    │
│  │  │                      │   │    │
│  │  └──────────────────────┘   │    │
│  └─────────────────────────────┘    │
└─────────────────────────────────────┘
LayerWhat It IsCSS Property
ContentThe actual text, image, or child elementswidth, height
PaddingSpace between content and borderpadding
BorderA line around the paddingborder
MarginSpace outside the border (between elements)margin

The Sizing Problem

By default, width and height only set the content size. Padding and border are added on top:

.box {
    width: 200px;
    padding: 20px;
    border: 5px solid #333;
}
/* Actual rendered width = 200 + 20 + 20 + 5 + 5 = 250px */

box-sizing: border-box

The fix is box-sizing: border-box, which makes width include padding and border:

* {
    box-sizing: border-box;
}

.box {
    width: 200px;
    padding: 20px;
    border: 5px solid #333;
}
/* Actual rendered width = 200px (padding and border fit inside) */

This is considered a best practice — most developers apply it to all elements with the universal selector *.

Margin Collapsing

When two vertical margins meet, they collapse — the larger margin wins instead of both being added:

.box-a { margin-bottom: 30px; }
.box-b { margin-top: 20px; }
/* Actual space between them = 30px (not 50px) */

This only happens with vertical margins, not horizontal.

Inspecting the Box Model

You can visualize the box model in your browser's Developer Tools:

  1. Right-click an element → Inspect
  2. In the Computed tab, you'll see a diagram of the box model
  3. Hover over the element to see the content (blue), padding (green), border (yellow), and margin (orange) highlighted

Key Takeaways

  • Every element is a box with content, padding, border, and margin
  • Use box-sizing: border-box so width includes padding and border
  • Vertical margins collapse — the larger one wins
  • Use DevTools to visualize and debug the box model