Box Model, Units and Typography

Every element is a box: master sizing, spacing, display types, positioning, units and readable text.

Beginner · about 5 hours · difficulty 2/5

Learn first: Selectors, Specificity and the Cascade

Every element renders as a rectangle made of content, padding, border and margin. Layout bugs usually come from misunderstanding one of those four layers.

Sizing and display

  • By default width sets the content box, so padding and border make the element wider than you asked. Almost every project sets *, *::before, *::after { box-sizing: border-box; }.
  • display: block fills the line; inline flows with text and ignores width/height; inline-block flows but respects sizing; none removes it.
  • Vertical margins between blocks collapse (the larger one wins), which surprises everyone once.
  • overflow decides what happens when content does not fit.

Positioning

static (default), relative (offset from itself, creates a positioning context), absolute (relative to the nearest positioned ancestor), fixed (relative to the viewport), sticky (switches between relative and fixed). z-index only works inside stacking contexts, which are created by positioning, opacity < 1, transform and others.

Units

  • px for hairlines and borders; rem for type and spacing (respects user font settings); em relative to the current font; % relative to the parent; vw/vh and the newer dvh/svh for viewport sizes; ch for line lengths.
  • clamp(1rem, 2.5vw, 1.5rem) gives fluid sizes with limits.

Typography and colour

Set a readable base size (around 16px), line-height near 1.5, line length of 45 to 75 characters, and load web fonts with font-display: swap. Check text contrast (4.5:1 for body text).

Move on when you can build a card component from scratch and explain every pixel of its size in DevTools' box model diagram.

Key concepts

  • Content, padding, border, margin
  • box-sizing: border-box
  • display types
  • Margin collapsing
  • position and stacking contexts
  • rem, em, %, vw and dvh
  • clamp(), min() and max()
  • Web fonts and font-display
  • Color formats and contrast: hex, rgb, hsl, oklch

Mini project

Build a pricing card and a sticky header with a dropdown, using rem-based spacing, a web font and fluid headings with clamp(); make sure the dropdown layers correctly above page content.

Check yourself

You set z-index: 9999 on a dropdown but it still appears behind another element. What are two possible causes?

Free resources