Skip to content

What makes a page janky: reflow and repaint

Deep diveUnder the hood

An animation stutters or a click takes a visible moment, and the profiler blames "Layout", not your JavaScript. Layout is not slow because the page is big; it is slow because your code makes the browser do it many times. Here is which changes re-run layout, how far one change spreads, and how reading a size in the middle of writing turns one layout into a thousand.

01 A loop that takes 100 ms

A list of cards should each grow by a pixel. The code is short and obviously linear:

grow.js
for (const card of cards) {
card.style.height = (card.offsetHeight + 1) + 'px';
}

With 1,000 cards this took about 110 ms in a recent Chrome on a Mac laptop, every time. Reading all the heights first and then writing them took under 4 ms. Same changes, same final page. The difference is how many times the browser had to lay out the page, and that is decided by the order of your reads and writes.

If the stages of rendering (style, layout, paint, composite) are new to you, read The DOM, layout and paint first; this page goes inside the layout stage.

02 Layout is lazy until you ask

Browsers do not lay out the page each time you change a style. A write only marks the affected boxes as needing layout. The real work happens once, just before the next frame is drawn, and covers every change made since the last one.

That is also why a single change can cost more than the one box you touched. Here is a width change on one card, as Blink (Chrome’s engine) typically handles it. Gecko and WebKit use similar dirty flags.

How far one width change spreads
Step 1 of 7
Layout tree of the page
body
main
card1
title
text
card2
footer
  • needs layout
  • flagged or moved
  • laid out now
  • clean

A clean page: body holds main and footer; main holds two cards; card 1 holds a title and a paragraph.

Blink keeps a layout cache: a box whose inputs, such as its available width, are unchanged can keep its last result and just be moved. Newer engines lean on this heavily, but anything that changes a width tends to spread downwards through the subtree, and anything that changes a height spreads upwards and onwards.

03 Which properties re-run layout

A property re-runs layout if it can change a box’s size or position, or the size or position of anything around it. The rest only repaint, and two common ones can skip paint as well.

What a style change typically re-runs in Chrome, Firefox and Safari
ChangeLayoutPaintComposite
width, height, min-/max-widthyesyesyes
margin, padding, border-widthyesyesyes
top, left, right, bottom (positioned)yesyesyes
font-size, font-family, line-height, font-weightyesyesyes
display, position, float, flex and grid propertiesyesyesyes
text content, adding or removing elementsyesyesyes
color, background, box-shadow, outline, border-colornoyesyes
visibilitynoyesyes
transform, opacity (on a composited layer)nonoyes

A class change costs whatever the properties it changes cost. Toggling a class that only changes color is a repaint; one that also changes padding is a layout. Engines differ in details, and the exact cost of a property can change between versions, so measure when it matters.

04 Reads that force layout now

Some APIs return geometry: sizes, positions, scroll offsets. If the layout is dirty when you call one, the browser cannot answer from stale numbers, so it runs style and layout immediately, inside your script. This is a forced synchronous layout, or forced reflow.

Common reads that force layout when it is dirty
APIExamples
Element box metricsoffsetWidth, offsetHeight, offsetTop, offsetLeft, offsetParent
Client and scroll metricsclientWidth, clientHeight, scrollWidth, scrollHeight, scrollTop
RectanglesgetBoundingClientRect(), getClientRects()
Computed style of layout valuesgetComputedStyle(el).width, .height, .top
Text that depends on layoutel.innerText
Actions that need positionsel.focus(), el.scrollIntoView(), document.elementFromPoint()

A read on its own is not the problem. If the layout is clean, the answer is already stored and costs almost nothing. The problem is a read after a write, inside the same task.

05 Reading layout mid-write

Here is the loop from the first section on three cards, followed by the fixed version.

Read, write, read, write: three cards
Step 1 of 8
cards in the loop
card 1
card 2
card 3
Layout state
layout tree→clean
Work done this frame
Empty
  • just happened
  • forced layout
  • layout dirty
  • not visited yet

The previous frame left the layout clean: every box has a known size. The loop is about to visit three cards.

0 layouts
All reads, then all writes
Step 1 of 4
cards in the loop
card 1
card 2
card 3
Layout state
layout tree→clean
Work done this frame
Empty
  • just happened
  • layout dirty
  • answered from cache

Same three cards, same clean layout. This time the code reads every height first and writes afterwards.

0 layouts

This is layout thrashing. The total work grows with the number of items times the cost of one layout, and one layout itself grows with the page. That is why it hides in small tests and appears with real data.

06 How to see it yourself

In Chrome DevTools, open the Performance panel, record while you trigger the code, and look inside your script’s task. Each forced layout is a purple Layout block under the function that read the size, and DevTools marks it with a warning about a forced reflow. A healthy frame has one Layout block, after the script.

For a number, time both versions. This is the script behind the figures in the first section; the results come from one machine and will differ on yours, but the ratio is what matters:

measure.js
// 1,000 cards, each with some padding and a border
const cards = [...document.querySelectorAll('.card')];
function interleaved() {
for (const c of cards) {
const h = c.offsetHeight; // read
c.style.height = (h + 1) + 'px'; // write
}
}
function batched() {
const hs = cards.map((c) => c.offsetHeight); // all reads
cards.forEach((c, i) => (c.style.height = (hs[i] + 1) + 'px')); // all writes
}
let t = performance.now();
Text
interleaved ~110 ms (three runs: 111.0, 110.3, 108.7)
batched ~2–4 ms (three runs: 3.8, 2.5, 2.4)

07 Keeping layouts few and small

Interleaved
for (const c of cards) {
c.style.height =
(c.offsetHeight + 1) + 'px';
}
Reads, then writes
const hs = cards.map((c) => c.offsetHeight);
requestAnimationFrame(() => {
cards.forEach((c, i) => {
c.style.height = (hs[i] + 1) + 'px';
});
});
  • Batch reads before writes. When code from different places shares a page, a common pattern is to queue writes and run them in requestAnimationFrame, so they happen together just before the frame.
  • Animate `transform` and `opacity`. Moving a box with transform: translateY() does not change its layout box, so neighbours are not laid out again.
  • Let the browser tell you. ResizeObserver and IntersectionObserver report sizes and visibility after layout has run, instead of you polling offsetHeight in a scroll handler.
  • Limit how far a change spreads. contain: layout tells the browser that nothing inside an element affects layout outside it, and content-visibility: auto skips layout for off-screen sections until they are near the viewport.

08 When reflow bites

window.addEventListener('scroll', () => { bar.style.width = window.scrollY / max * 100 + '%'; label.textContent = el.getBoundingClientRect().top; });Writes and reads in a scroll handlerA scroll event can fire many times per frame, and each write-then-read pair forces a layout. Read first, write in requestAnimationFrame, or use an observer.
@keyframes grow { to { height: 300px; } }Animating a layout propertyAnimating height, top or margin re-runs layout on every frame, often for everything below it. Animate transform: scale() or translate() instead, or use a single-frame change.
el.classList.add('open'); const h = el.scrollHeight;Measuring right after a class changeThe class may change layout properties, so the next geometry read forces layout. It is fine once; inside a loop over many elements it is thrashing.
<img src="photo.jpg">Images with no sizeUntil the image loads the browser does not know its height, so the content below jumps when it does. Give width and height attributes (or aspect-ratio) so the box is right from the first layout.
const w = getComputedStyle(el).width;Hidden reads in helpersLibrary calls such as "get outer height" or "is visible" often read geometry under the hood. Profile before assuming a loop only writes.

09 Check yourself

Question

A loop over 50 elements sets el.style.color and then reads el.offsetWidth. How many forced layouts does it typically cause?

Question

Which change can move an element on screen without its neighbours being laid out again?

Question

Why does reading offsetHeight after a write force a layout, when the same read before the write does not?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?