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
widthsets 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: blockfills the line;inlineflows with text and ignores width/height;inline-blockflows but respects sizing;noneremoves it.- Vertical margins between blocks collapse (the larger one wins), which surprises everyone once.
overflowdecides 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
pxfor hairlines and borders;remfor type and spacing (respects user font settings);emrelative to the current font;%relative to the parent;vw/vhand the newerdvh/svhfor viewport sizes;chfor 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
- The box model (MDN)
- Learn CSS: Box Model (web.dev)