← Lessons

quiz vs the machine

Silver1120

Frontend

Layout and Reflow

Why reading a width can force the browser to recompute geometry.

5 min read · intro · beat Silver to climb

What layout computes

Layout, sometimes called reflow, is where the browser figures out the exact position and size of every box. It walks the render tree and resolves widths, heights, and offsets.

What triggers a reflow

  • Changing geometric properties like width, height, margin, or font size.
  • Adding or removing nodes from the DOM.
  • Reading a layout value such as offsetWidth or getBoundingClientRect right after a write.

Layout thrashing

The last point causes a classic bug. If you alternate writing a style and then reading a measured value in a loop, the browser must flush layout each time so the read is accurate. This is layout thrashing and can stall a frame badly.

How to avoid it

  • Batch reads, then batch writes so the browser computes layout once.
  • Cache measured values instead of re-reading them inside loops.
  • Prefer transform over top and left for movement, since transform does not reflow.

Cost scales with subtree

A reflow can be local or can cascade to ancestors and descendants. Touching a deeply nested, wide subtree is far more costly than a leaf.

Key idea

Reflow recomputes box geometry; interleaving writes and reads forces it repeatedly, so batch your reads and writes.

Check yourself

Answer to earn rating on the learn ladder.

1. What is layout thrashing?

2. Which property avoids triggering reflow for movement?

3. How do you minimize forced reflows in a loop?