liveBook · Manning

CSS box model

As explained in Math for Web Design

The CSS box model describes each element as a rectangular box composed of content, padding, border, and margin areas.

The CSS box model treats every element as a rectangle whose content is surrounded by padding, border, and margin. Its arithmetic explains the space an element actually occupies, making sizing problems easier to predict and troubleshoot. section 3.5

In the default box model, rendered dimensions are calculated by adding the element’s declared or computed content size to its inner edges:

  • Total width = width + left and right padding + left and right border widths. section 3.5.1
  • Total height = height + top and bottom padding + top and bottom border widths. section 3.5.1
  • Margin contributes spacing around the element, while padding and borders contribute to the rendered box dimensions described by these formulas. section 3.5

Why a 300px box becomes 360px wide

With width: 300px, padding: 20px, and a 10px border, the rendered width is 300px + 20px + 20px + 10px + 10px = 360px. The declared width is therefore not necessarily the final space occupied on the page. section 3.5.1

width + padding-left + padding-right + border-left-width + border-right-width

Use the width formula as a compact reference for checking which horizontal dimensions contribute to an element’s rendered size. section 3.5.1

The same accounting matters in CSS Grid. For a border-box grid container, subtract fixed tracks, gaps, horizontal borders, and horizontal padding before distributing the remaining space among fr units. In an 800px container with 200px of fixed tracks, 60px of gaps, 12px of borders, and 30px of padding, 498px remains; 2fr receives 332px and 1fr receives 166px. section 4.3.3

How Math for Web Design covers it

How deep it goes
Explains width and height formulas and applies them to fixed boxes and Grid track calculations.
Examples
Calculates a 300px box with 20px padding and 10px borders, then distributes remaining space across 2fr and 1fr Grid tracks.
What it assumes
Assumes basic CSS declarations and layout familiarity while developing the arithmetic needed to interpret rendered dimensions.
What you can do after
Diagnose sizing and Grid-layout discrepancies by accounting for padding, borders, gaps, fixed tracks, and content dimensions.
How it connects
Connects the box model to CSS Grid, padding, borders, margins, and box-sizing.

Also explained in

Compare how 6 books explain CSS box model →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Math for Web Design. The section links point to the parts of the book it draws on.