CSS Box Model & Layout
The problem
Every visible element on a page needs a computed size and position before it can be drawn — layout is the process that turns the render tree's abstract 'what should appear' into concrete pixel coordinates and dimensions for every single element.
Why now
HTML parsing and the render tree produced the set of elements that will be visible, but not where or how large each one is. The box model is the specific rule set (content, padding, border, margin) that answers that question for every element, and layout is the algorithm that applies it across the whole tree.
Mental model
Every element is a rectangular box made of four nested layers — content, padding, border, margin — and layout is a tree-wide computation of every box's final size and position, where each box's dimensions can depend on its parent's and its children's. This is exactly why changing one element's size can ripple through and reposition many others: layout is not local, it's a tree-wide consequence.
Requires
- HTML Parsing & the Render TreeBrowser Internals
Layout computes size and position for exactly the nodes the render tree contains; you need the render tree as the set of boxes being laid out before layout's job is well-defined.
Unlocks
Used in
- Every visual CSS property that affects size or position (width, padding, flexbox, grid)
- Understanding 'layout thrashing' — repeatedly reading and writing layout-affecting properties in a loop, forcing repeated recalculation
- Responsive design, where layout is recomputed as viewport size changes
- Flexbox and Grid as higher-level layout algorithms built on the same box-model foundation
Projects
- Use browser DevTools to inspect the box model breakdown (content, padding, border, margin) of a real element and match it to the rendered pixels
- Deliberately trigger layout thrashing (reading offsetHeight in a loop after writes) and measure the performance cost versus a batched version
Examples
- box-sizing: border-box changes whether padding and border are included inside or added outside the specified width
- Reading element.offsetHeight immediately after changing a style forces the browser to recompute layout synchronously, which is expensive in a loop
Resources
- MDN — The box modelarticle
Mastery checklist
- I can diagram the box model's four layers and explain what each contains
- I can explain the difference between content-box and border-box sizing
- I can explain why layout is a tree-wide computation, not a per-element local one
- I can identify and fix a layout-thrashing pattern in real code