Skip to content
FrontDepth, Home

Browser & Performance

Reflow, repaint and layout thrashing

What the browser does after a DOM or style change — style, layout, paint and compositing — from which CSS changes cost what, to forced synchronous layout, layout thrashing, cheap animations, CSS containment and finding reflows in DevTools.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

This topic starts at Junior level.

JuniorConcept

The frame pipeline: from a change to pixels

The topic follows HTML and CSS to the first pixels. This topic is about everything after that: each time JavaScript changes the DOM or a style, the browser has to bring the screen up to date, and it does so in the same stages, frame by frame:

  1. JavaScript — your code changes something: a class, an inline style, a text node, a new element.
  2. Style — the browser works out which elements are affected and recalculates their computed styles.
  3. Layout — it computes the size and position of the boxes that may have moved. Reflow is another name for layout; Chrome DevTools labels it "Layout".
  4. Paint — it records how to draw the affected parts: text, colors, borders, shadows, images. A repaint is a paint without layout before it.
  5. Composite — it combines the painted layers into the frame that appears on screen.

Not every change goes through all five stages. A change of width runs all of them; a change of color skips layout; a transform change on an element with its own layer can skip layout and paint. The next section shows which change takes which path.

The frame budget

A 60 Hz display shows a new frame about every 16.7 ms, a 120 Hz display every 8.3 ms. Everything for one frame — your JavaScript, style, layout, paint — has to fit into that window, and the browser needs part of it for its own work; web.dev suggests keeping your share to about 10 ms at 60 Hz. When the work does not fit, frames are dropped: scrolling stutters, animations jump, typing feels late.

The browser is lazy, on purpose

Writing styles is cheap. The browser does not lay the page out after every assignment; it marks the affected parts as out of date ("dirty") and does the real work once, in the next rendering update:

JavaScript
button.addEventListener("click", () => {
  panel.classList.add("open");
  panel.style.width = "320px";
  panel.style.padding = "16px";
});

Three writes, but only one style recalculation and one layout before the next frame. Most rendering performance problems come from breaking this laziness: making the browser do layout many times inside one task, or making each frame do more layout and paint than it needs.

JuniorWeb platform

Which changes cost layout, paint or only compositing

The path a change takes depends on what it can affect.

ChangeExamplesStages
Box geometrywidth, height, padding, margin, border-width, top/left on a positioned element, font-size, displaystyle → layout → paint → composite
Contenttext changes, adding or removing nodes, an image arriving without width/height, a web font replacing the fallbackstyle → layout → paint → composite
Appearance onlycolor, background-color, box-shadow, outline, visibilitystyle → paint → composite
Compositortransform, opacity on an element with its own layerstyle → composite

Why layout is the expensive one

Layout is usually scoped to the whole document. Making one element taller pushes everything below it down, a wider sidebar squeezes the main column, and a longer heading can wrap onto a second line and change the height of its card. The browser has to work out who is affected, and on a large DOM that takes time. Some layout changes are not caused by your CSS at all: a scrollbar that appears changes the width of the page, and resizing the window re-runs layout for everything that depends on the viewport.

Paint cost depends on how much area has to be repainted and how expensive it is to draw: a large box-shadow or a filter: blur() costs more than a flat color.

Compositing is the cheapest path. If an element is on its own layer, the compositor can move it, scale it or fade it by recombining layers that are already painted, without touching layout or paint.

Style recalculation is not free either

Every change starts with style. Adding a class to <body> can invalidate the computed style of every element in the page, while adding it to one leaf element affects only that element. Fewer affected elements and simpler selectors make this stage cheaper.

Check it, don't memorize it

Engines differ, and details change between versions. For example, in Chromium the first change of transform away from none, or of opacity away from 1, can still run style and layout once, because the element starts forming a new stacking context; the following changes take the compositor path. Instead of trusting a list, check in DevTools: the Rendering drawer has Paint flashing (repainted areas flash green) and Layout Shift Regions, and the Performance panel shows each Layout and Paint event.

MiddleWeb platform

Reading layout forces it: forced synchronous layout

The laziness from the first section has one exception. JavaScript is allowed to ask for geometry at any moment, and the answer must be correct. If styles or the DOM changed since the last layout, the browser cannot answer from stale data, so it stops your script, recalculates style, runs layout right away, and only then returns the value. That is a (Chrome calls it a forced reflow).

JavaScript
card.classList.add("expanded");
const height = card.offsetHeight;

The first line only marks style as dirty. The second line needs the new height, so style and layout run inside your task, before the browser would have done them anyway.

What forces layout

Based on Paul Irish's list, compiled from the Blink source, the common ones are:

  • box metrics: offsetTop/Left/Width/Height, clientTop/Left/Width/Height, getBoundingClientRect(), getClientRects();
  • scrolling: scrollWidth, scrollHeight, reading or setting scrollTop/scrollLeft, scrollTo(), scrollBy(), scrollIntoView();
  • element.focus(), innerText, document.elementFromPoint(), window.scrollX/scrollY, and the offsetX/offsetY of a mouse event;
  • getComputedStyle(): it always brings style up to date, and it forces layout when you read a layout-dependent value such as width, height, top, margin, padding or transform.

Reading element.style.width, classList, dataset, attributes or textContent does not force layout: these values come from the DOM, not from the layout tree.

When it costs nothing

A read is only expensive when something is dirty. Reading offsetWidth twice in a row costs one layout at most; reading it when nothing has changed since the last frame returns a cached value. That is why the advice is "read before you write": at the start of an event handler, the layout from the last frame is usually still valid.

JavaScript
input.addEventListener("input", () => {
  const width = list.clientWidth;
  list.classList.toggle("compact", width < 480);
  counter.textContent = String(input.value.length);
});

The read happens before any write in this task, so it is cheap unless something else changed the page since the last frame.

Why one forced layout matters

A single forced layout is not a disaster: it moves work earlier instead of adding it. It becomes a problem when it happens inside a hot path — a scroll handler, a mousemove listener, an animation loop — or when every forced layout lays out a large DOM. And it becomes a serious problem when it repeats in a loop, which is the next section.

MiddleExample

Layout thrashing and how to fix it

is a loop that alternates writes and layout reads, so every iteration pays for a full layout. A bar chart is the classic case:

JavaScript
function drawChart(bars, values) {
  bars.forEach((bar, i) => {
    bar.style.height = `${values[i] * 2}px`;
    const label = bar.querySelector(".label");
    label.style.top = `${bar.offsetHeight + 4}px`;
  });
}

Each bar.offsetHeight read comes right after a write, so with 30 bars the browser lays the page out 30 times in one task instead of once. The platform's Layout thrash challenge is exactly this situation: a 30-bar chart where every bar forces a layout, and you measure the forced layouts while fixing it.

Fix 1: don't read what you already know

The height was just computed from values[i]. Use the number instead of asking the DOM:

JavaScript
function drawChart(bars, values) {
  bars.forEach((bar, i) => {
    const height = values[i] * 2;
    bar.style.height = `${height}px`;
    bar.querySelector(".label").style.top = `${height + 4}px`;
  });
}

Fix 2: batch reads, then writes

When you do need measurements, take all of them first and write afterwards. The reads share one layout; the writes only mark things dirty.

JavaScript
const widths = cards.map((card) => card.getBoundingClientRect().width);
cards.forEach((card, i) => {
  card.style.height = `${widths[i] * 0.75}px`;
});

Fix 3: cache measurements, and invalidate them

A container width read once and reused is free. The cache must be refreshed when the size really changes. Polling with a timer or a loop is the wrong tool for that; ResizeObserver is the right one. Its callback runs during the rendering update, after layout and before paint, so it gets the new size without forcing an extra layout:

JavaScript
let containerWidth = container.clientWidth;
new ResizeObserver(([entry]) => {
  containerWidth = entry.contentRect.width;
}).observe(container);

If the callback itself changes layout, the browser runs layout again within the same frame, and it reports "ResizeObserver loop completed with undelivered notifications" when this does not settle.

Fix 4: schedule writes with requestAnimationFrame

When many independent pieces of code read and write (widgets, plugins, a library and your app), collect writes in a queue and flush them in one requestAnimationFrame callback; libraries such as FastDOM do exactly this. Note that rAF moves the writes to the next frame but does not fix a read-after-write loop inside the callback, and it changes when the DOM is updated, which matters for code that expects the result immediately.

MiddleWeb platform

Animating transform and opacity, and the cost of will-change

An animation is a change on every frame. If it animates left, top, width or height, every frame runs style, layout and paint, on the , where your JavaScript also runs. One long task and the animation stutters.

transform and opacity are the two properties browsers can animate cheaply. When the element is on its own layer, a new frame only needs : the already painted layer is moved, scaled or faded. CSS animations and transitions of these properties can run on the compositor thread, so they keep going even while the main thread is busy. A JavaScript animation that sets a transform from requestAnimationFrame skips layout and paint as well, but it still needs the main thread on every frame.

CSS
.toast-enter-bad {
  animation: slide-bad 200ms ease-out;
}
@keyframes slide-bad {
  from { top: -64px; }
  to { top: 0; }
}

.toast-enter {
  animation: slide 200ms ease-out;
}
@keyframes slide {
  from { transform: translateY(-64px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

A transform does not change layout: neighbours do not move, and offsetWidth keeps reporting the layout box. That is what makes it cheap and also what limits it. To animate a real layout change (a list item moving to a new position, a card expanding), the FLIP technique measures the First and Last positions, applies an Inverting transform so the element looks unchanged, and then Plays a transition of that transform back to none. The layout changes once; the animation itself is compositor work.

will-change: a hint with a price

will-change: transform tells the browser to prepare the element in advance, typically by giving it its own layer, so the first frame of the animation does not have to do that work. MDN calls it a last resort for an existing performance problem, not something to add in advance:

  • every layer costs memory (on the GPU, for its painted pixels) and management time; promoting hundreds of elements can make the page slower, especially on low-memory phones;
  • will-change with a property that would create a stacking context (transform, opacity) creates it immediately, which can change how z-index and position: fixed children behave;
  • left in a stylesheet, it keeps the optimization alive forever. Turn it on just before the animation and remove it afterwards.
JavaScript
menu.addEventListener("pointerenter", () => {
  menu.style.willChange = "transform";
});
menu.addEventListener("transitionend", () => {
  menu.style.willChange = "auto";
});

Old code uses transform: translateZ(0) as a hack to force a layer; will-change states the intent directly. Confirm the effect in the DevTools Layers panel, which shows each layer and why it was created.

SeniorWeb platform

CSS containment: contain and content-visibility

Layout is usually document-wide because the browser cannot know that a change inside one widget will not affect the rest of the page. CSS containment is a promise that it will not, and the browser uses the promise to limit work.

The contain property

  • contain: layout — nothing inside affects the layout outside. The element becomes a containing block for absolute and fixed descendants and creates a stacking context.
  • contain: paint — descendants are clipped to the element's box, and when the box is off-screen its contents need not be painted.
  • contain: size — the element's size does not depend on its children, so you must give it a size.
  • contain: style — counters and quotes do not leak out.
  • Shorthands: content = layout paint style (safe for most independent widgets); strict = content plus size.
CSS
.feed-item {
  contain: content;
}

A feed item, chat message, comment or third-party embed is a good candidate: when its content changes, layout and paint can stay inside it. contain works in all modern browsers.

content-visibility: skip what is off-screen

content-visibility: auto turns on layout, style and paint containment and, while the element is far from the viewport, skips its contents entirely: no style, layout or paint for that subtree until the user scrolls near it. On long pages (articles, documentation, long feeds) this can remove most of the initial rendering work.

CSS
.article-section {
  content-visibility: auto;
  contain-intrinsic-size: auto 600px;
}

A skipped element is sized as if it were empty, so give it a placeholder size with contain-intrinsic-size. Without it, off-screen sections collapse to zero height, the scrollbar is wrong, and the page jumps as sections render. The auto keyword makes the browser remember the last rendered size and use it when the section is skipped again.

content-visibility: hidden always skips the contents (like display: none, but the rendering state is kept, so showing it again is cheaper). With auto, skipped content stays in the accessibility tree and still works with find-in-page, focus and tab order; with hidden it cannot be found, focused or reached with Tab.

MDN lists content-visibility as Baseline 2024; in Safari before version 26, skipped auto content was not found by find-in-page.

Trade-offs

  • Reading geometry inside a skipped subtree (offsetHeight of a child) forces the browser to lay it out, which cancels the benefit. Measure the container, not its contents.
  • content-visibility keeps every DOM node: memory and DOM size stay. For tens of thousands of rows, virtualization (rendering only the visible rows) is still the tool; the List virtualization topic covers it.
  • Containment changes behaviour (clipping, stacking contexts, containing blocks), so add it only where a component is truly independent.
SeniorFramework

Finding reflows in DevTools and in React apps

Reading a Performance recording

Record the slow interaction in the Chrome DevTools Performance panel, with CPU throttling on so a fast laptop behaves more like a phone. In the Main track, yellow is scripting, purple is rendering (Recalculate style, Layout) and green is painting.

  • A healthy frame does its style and layout once, after your task has finished.
  • A forced layout shows up inside a script: a purple Layout block nested under your function call. DevTools marks such events with a warning and links to the line of JavaScript that forced them.
  • Thrashing looks like a comb: dozens of narrow purple Layout blocks under one task.
  • The Insights sidebar has a Forced reflow insight (Chrome 134 and later). It names the function with the most forced reflow time and its stack trace; its passing criterion is no forced reflow longer than 30 ms.

For paint, open the Rendering drawer: Paint flashing shows what is repainted on each frame, and Layer borders together with the Layers panel show which elements were promoted and why.

React does the batching, you can still break it

React applies all DOM changes of a commit together, so the framework itself does not thrash. Your code can: useLayoutEffect runs synchronously after React has changed the DOM and before the browser paints, so a measurement there forces a layout whenever the commit changed the DOM. One measurement per commit (positioning a tooltip, say) is fine and is what the hook is for. The problem appears when every row of a list measures itself and writes, here to snap its height to an 8px grid:

JSX
import { useLayoutEffect, useRef } from "react";

function Row({ text }) {
  const ref = useRef(null);
  useLayoutEffect(() => {
    const height = ref.current.offsetHeight;
    ref.current.style.minHeight = `${Math.ceil(height / 8) * 8}px`;
  });
  return <li ref={ref}>{text}</li>;
}

Layout effects of all rows run one after another in the same task, so row 2 reads after row 1 wrote, and so on: one forced layout per row. Measure once in the parent, use a shared ResizeObserver, or solve it in CSS (container queries, grid with auto rows) so nothing has to be measured at all.

Not every jank is layout

An input can feel slow while the recording shows yellow, not purple: the time goes to scripting (in a React app, often rendering many components on every keystroke), not to layout. Layout tricks will not help there; less script work will. Always look at the recording first and reduce the work of the colour that dominates. The Typing lag challenge is a good place to practise reading such a recording. Long tasks during interactions also make INP worse, which the Core Web Vitals topic covers.

SeniorInterview tips

Interview tips

  • Define the terms precisely. Reflow = layout: computing the geometry of boxes. Repaint = paint without layout: redrawing pixels whose geometry did not change. Compositing = combining painted layers. Say which CSS changes reach which stage, and add that engines differ and you would confirm it in DevTools.
  • Explain laziness first, then the exception. Writes only mark the page dirty; the browser does style and layout once per frame. A geometry read (offsetHeight, getBoundingClientRect(), layout-dependent getComputedStyle() values) on a dirty page forces that work immediately. Layout thrashing is that read inside a loop of writes.
  • Give the fixes in order of preference. Do not read what you can compute; batch reads before writes; cache measurements and refresh them with ResizeObserver; schedule writes with requestAnimationFrame when many parts of the code touch the DOM. Mention that rAF changes timing, so it is not a free fix.
  • Animations: animate transform and opacity, use FLIP for layout changes, and describe will-change as a targeted hint with a memory cost, not a global speed switch.
  • Senior depth: CSS containment (contain: content, content-visibility: auto with contain-intrinsic-size), its trade-offs against virtualization, and how React's useLayoutEffect can turn many small measurements into thrashing.
  • Show how you would find it. A Performance recording with CPU throttling, purple Layout blocks nested inside scripts, the Forced reflow insight, Paint flashing. Measure before and after; a number ("30 forced layouts per click, now 0") is a better answer than "it felt faster".

Misstatements to avoid:

  • "Changing a style triggers reflow immediately" — it marks the page dirty; reading geometry or the next frame triggers the work.
  • "transform is always free" — it needs a layer, layers cost memory, and the first change can still run layout.
  • "requestAnimationFrame fixes layout thrashing" — it only moves work to the next frame; a read-after-write loop inside it still thrashes.
  • "will-change everywhere makes the page faster" — too many layers make it slower.
JuniorReview checklist

What to check when reviewing code for reflow and repaint

Use this list when you review code you did not write (a teammate's pull request, a library's snippet or an AI assistant's suggestion) that changes the DOM or styles. One geometry read in the wrong place can force dozens of layouts in one task, and scrolling and animations stutter.

  • In a loop, does a geometry read (offsetHeight, getBoundingClientRect(), scrollTop) follow a style or DOM write? That is : a full layout per iteration. Use the value you already know, or do all reads before all writes. Wrapping the loop in requestAnimationFrame only moves it to the next frame.
  • Do scroll or mousemove handlers read layout on every event? Each read there can be a , many times per second. Cache the size and refresh it with a ResizeObserver, not with a timer.
  • Does an animation change top, left, width or height? Then every frame runs layout and paint on the . Animate transform and opacity instead, and check with Paint flashing in the DevTools Rendering drawer.
  • Is will-change set on many elements or left in the stylesheet for good? Every layer costs memory, and its stacking context can change how z-index works. Add it just before an animation, remove it afterwards; the Layers panel shows every layer.
  • In React, does each list row's useLayoutEffect read a size and then write a style? The effects run one after another, so every row forces its own layout. Measure once in the parent or share one ResizeObserver.
  • Is the fix proven by Performance recordings from before and after, with CPU throttling? Look for purple Layout blocks nested inside scripts and for forced reflow warnings.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.