Reading offsetHeight can make the browser run layout immediately, before the next line of your JavaScript runs. This is a forced synchronous layout, and inside a loop it can turn a list update into a page that stops responding for a third of a second. This article is part 2 of the series “How the browser turns CSS into pixels”, after part 1.
A 1,000-box page with two loops
The page below creates 1,000 boxes and changes the height of each one in two ways. Both functions read every box’s offsetHeight and write a new style.height. They differ only in the order of reads and writes. Save the page as an HTML file, open it in a browser and click Run.
<!doctype html>
<meta charset="utf-8">
<title>Forced layout test</title>
<style>.box { width: 50%; padding: 4px; }</style>
<button id="go">Run</button>
<pre id="out"></pre>
<div id="list"></div>
<script>
const list = document.getElementById('list');
for (let i = 0; i < 1000; i++) {
const d = document.createElement('div');
d.className = 'box';
d.textContent = 'Item ' + i + ' with some text that wraps when the box gets narrow enough to wrap';
list.appendChild(d);
}
const boxes = [...document.querySelectorAll('.box')];
function interleaved() {
for (const box of boxes) {
const h = box.offsetHeight; // read
box.style.height = (h + 1) + 'px'; // write
}
}
function batched() {
const heights = boxes.map(box => box.offsetHeight); // all reads
boxes.forEach((box, i) => { // then all writes
box.style.height = (heights[i] + 1) + 'px';
});
}
function reset() { boxes.forEach(b => b.style.height = ''); list.offsetHeight; }
function time(fn) { reset(); const t = performance.now(); fn(); list.offsetHeight; return (performance.now() - t).toFixed(1); }
function run() {
const r = [];
for (let i = 0; i < 5; i++) r.push(`interleaved: ${time(interleaved)} ms batched: ${time(batched)} ms`);
return navigator.userAgent + '\n' + r.join('\n');
}
document.getElementById('go').onclick = () => {
document.getElementById('out').textContent = run();
};
</script>
time() calls reset() first, which removes the heights and reads list.offsetHeight, so each run starts with nothing left to lay out. After the function, time() reads list.offsetHeight once more. That way the time includes the work the writes left behind.
Before you click, predict the result. Both functions do 1,000 reads and 1,000 writes. How far apart will the two times be?
In one run in Chromium 156 on macOS, the five interleaved times were between 333.6 and 349.6 ms. The five batched times were between 8.7 and 10.5 ms. So the interleaved loop was 30 to 40 times slower. Your numbers will differ with your machine and browser.
The reads alone are not the slow part. Paste this into the console of the same page:
reset();
const t = performance.now();
for (const box of boxes) box.offsetHeight;
console.log((performance.now() - t).toFixed(2), 'ms');
In the same run, 1,000 reads on a page where nothing had changed took 0.30 ms.
Layout is the step where the browser computes the size and position of every box on the page. In interleaved, each write changes a box’s height, so the next read finds the layout out of date. The browser cannot return a height from out-of-date boxes, so it brings styles and layout up to date before offsetHeight returns. A forced synchronous layout is layout that runs during your script because a read needs it, earlier than the browser would have run it (web.dev).
This article calls it a forced layout for short. interleaved forces 1,000 of them. batched forces one, in the final read inside time().
Rule: A layout read is cheap when nothing has changed since the last layout, and costly right after a write.
Writes only mark the page as out of date
A write such as box.style.height = '40px' does no layout at all. In Blink, the engine in Chrome and Edge, an inline style write ends in Node::SetNeedsStyleRecalc(). That call stores a note on the element that its style must be computed again. It also marks each ancestor as having a descendant that needs style, and schedules a frame.
That note is a dirty flag, a bit on a node or box that says “this is out of date”. It is set when something changes and cleared when the work is done.
Layout dirty flags come one step later. Style recalculation is the step that computes each element’s final CSS values from the style sheets and inline styles. During it, Blink compares the old and new style. When the change can affect size or position, LayoutObject::StyleDidChange() marks the box as needing layout.
Then MarkContainerChainForLayout() walks up the containing boxes and sets a “child needs layout” flag on each one. The walk stops at the first ancestor that is already marked. So repeated writes between two reads are cheap to mark, because each walk ends quickly.
WebKit and Gecko, the engines in Safari and Firefox, work the same way. WebKit’s markContainingBlocksForLayout() and Gecko’s PresShell::FrameNeedsReflow() also walk up and stop at an ancestor that is already dirty.
Rule: A write sets dirty flags and schedules a frame. The layout work waits for a read or for the next frame.
A forced synchronous layout runs before the read returns
A read goes the other way. This is Blink’s path for offsetHeight, shortened from the source at one pinned commit:
HTMLElement::offsetHeightForBinding() html_element.cc
Document::UpdateStyleAndLayoutForNode(this) document.cc
Document::UpdateStyleAndLayout() document.cc
parent frame's document first
LocalFrameView::UpdateStyleAndLayout() local_frame_view.cc
style recalculation
if (NeedsLayout()) UpdateLayout();
return the box's offset height
The JavaScript property calls offsetHeightForBinding(). Before it reads anything, it calls UpdateStyleAndLayoutForNode(). A comment there says that any location-based calculation needs up-to-date style and layout. offsetTop, getBoundingClientRect(), clientHeight and scrollTop take the same path.
The check that decides the cost is if (NeedsLayout()) { UpdateLayout(); } in UpdateStyleAndLayoutInternal(). When no layout dirty flag is set, layout never runs and the read costs only the checks. That is why 1,000 clean reads took 0.30 ms. When a flag is set, layout runs now, and your script waits until it finishes.
Gecko has the same gate. A layout flush returns at once when NeedFlush() finds no style or layout work.
The update covers the whole document, including parts far from the element you read. UpdateStyleAndLayout() brings the document up to date, and the documents of parent frames first. So reading a.offsetHeight pays for a dirty box anywhere on the page, even in a part that has nothing to do with a. How much of the tree gets laid out depends on the dirty flags and on relayout boundaries, covered further down.
Note: WebKit has one extra shortcut. For
offsetHeightandgetBoundingClientRect(),updateLayoutIfDimensionsOutOfDate()skips layout when no dirty flag could change the requested size.
No spec tells the browser to force layout
CSSOM View defines offsetHeight through boxes. It is the height of the bounding box around the border boxes of the element’s fragments, or zero if the element has no box (CSSOM View). The definition says nothing about when layout runs.
But the getter runs synchronously, and its value must match the current boxes. So an engine whose boxes are out of date has to lay them out before it answers.
The HTML spec describes where layout happens in the normal case. When the browser has a chance to render, the event loop runs a task to update the rendering, the list of steps that produces one frame (HTML). One step reads “Recalculate styles and update layout”. That phrase is plain text, with no algorithm behind it and no idea of a forced layout.
The Long Animation Frames spec says the same from the other side. It states that when style and layout run is implementation-defined, and an open issue in it asks how to make this interoperable (LoAF spec). Forced layout is how engines meet a synchronous getter defined over boxes. No spec lists it as a step.
The figure shows the order of the steps in update the rendering, and a forced layout for comparison.
A normal frame (update the rendering)
requestAnimationFrame callbacks
|
v
style and layout <-------------+
| | again, while callbacks
v | change observed sizes
ResizeObserver callbacks -------+
|
v
intersection observations
|
v
paint
Forced layouts (inside your script, before any frame)
box.style.height = ... sets dirty flags
box.offsetHeight style and layout run now; the script waits
box.style.height = ... sets dirty flags again
box.offsetHeight style and layout run again
In a normal frame, style and layout run once, after the requestAnimationFrame callbacks.
ResizeObserver is an API that calls you back when an element’s size changes. Its callbacks run inside the layout loop, so they see sizes from the frame’s own layout. IntersectionObserver reports when an element crosses the edge of the viewport or another root, and its observations come next. A script that reads layout between writes pulls that work out of the frame and repeats it.
Layout thrashing repeats the cost for every pair
Chrome’s documentation uses the name “forced reflow” for a forced layout. It calls several forced layouts in quick succession layout thrashing (Chrome for Developers, October 8, 2025). The interleaved loop is layout thrashing with 1,000 forced layouts.
Each forced layout also gets more expensive as the page grows. Paste this into the console of the test page:
function pairs(n) {
for (const box of boxes.slice(0, n)) {
const h = box.offsetHeight;
box.style.height = (h + 1) + 'px';
}
}
console.log('250 pairs, 1,000 boxes shown:', time(() => pairs(250)), 'ms');
boxes.slice(250).forEach(b => b.style.display = 'none');
console.log('250 pairs, 250 boxes shown:', time(() => pairs(250)), 'ms');
boxes.forEach(b => b.style.display = '');
In the Chromium 156 run, 250 write/read pairs took 88.6 ms with all 1,000 boxes on the page. With only 250 boxes shown, the same 250 pairs took 28.1 ms.
A loop over every element of a page with n elements does n forced layouts, and each one grows with n. So the loop costs roughly n² work. In this run, four times as many boxes made the full loop about 12 times slower (28 ms for 250 boxes, about 340 ms for 1,000). This n² estimate is reasoning from these numbers; no browser vendor publishes such a figure.
While layout runs, the main thread does nothing else. Clicks, key presses, timers and painting wait until the loop ends. In Gecko, a layout flush that script forces is not interruptible (PresShell.cpp).
The Firefox docs add, about Firefox’s own interface, that one forced layout costs no more than the same layout in a normal frame (Firefox docs). The cost comes from where it runs and how often.
Interaction to Next Paint (INP) is the Core Web Vital that measures how long a page takes to show the next frame after a user interaction. web.dev rates 200 ms or less as good and over 500 ms as poor (web.dev). The 340 ms loop from the example, run in a click handler, is past the good limit on its own. By our reasoning, a forced layout moves layout time into the handler, and thrashing adds layouts that would not run at all otherwise (web.dev, Optimize INP).
Relayout boundaries limit how much each forced layout redoes
MarkContainerChainForLayout() has a second place to stop. A relayout boundary is a box whose contents cannot change its own size, so layout can start from it instead of from the root. Blink’s ObjectIsRelayoutBoundary() accepts two main kinds of box.
One has both layout and size containment, which contain: strict or contain: size layout gives. The other has a fixed width and height, with overflow clipped in both directions.
The CSS contain property tells the browser that an element’s inside is independent of the rest of the page (MDN). contain: layout alone does not make a relayout boundary in any of the three engines. Blink, WebKit (isLayoutBoundary()) and Gecko (CanBeDynamicReflowRoot()) all need size containment too.
The CSS Containment spec warns that contain: content leaves out size containment, so invalidation can spread further up the tree. It recommends contain: strict where possible (CSS Containment 2).
Containment has costs. Size containment makes the element ignore its contents when it sizes itself, so you have to give it a size. Layout containment also creates a stacking context and a containing block for fixed and absolutely positioned children (CSS Containment 2). In Blink, flex items, grid items and table parts can never be relayout boundaries.
Containment makes each forced layout smaller, and the number of forced layouts stays the same.
getComputedStyle forces layout only for some properties
getComputedStyle() returns one of two kinds of value for each property. A used value is the value after layout, such as a width in pixels. A computed value is the value after style recalculation and before layout. CSSOM returns the used value for width, height, margins and padding of a rendered element, and the computed value for most other properties (CSSOM).
So getComputedStyle(el).width can force layout, while getComputedStyle(el).color forces only style recalculation. Blink checks each property before it decides to run layout (source).
No spec lists every read that forces layout. The list most people cite is Paul Irish’s gist, What forces layout / reflow. Its footer says it was last updated in April 2020, so its source line numbers date from 2020 and some entries no longer match current engines.
Read everything first, then write
The batched function is the main fix, done by hand. All reads come first and share one layout, or none if nothing was dirty. All writes come after, and the browser lays them out once, in the next frame or at the next read. web.dev recommends this order, because reads done first can use the previous frame’s layout (web.dev).
The cost is the discipline. You have to restructure the code so that reads come first, and the order holds only while every piece of code in the loop follows it. A third-party script or a framework hook that reads after a write in the middle brings the forced layouts back.
FastDOM is a small library that queues reads and writes from anywhere in your app. It runs them in the next animation frame, all reads first, then all writes (FastDOM README).
// Excerpt: needs the fastdom library, and elements el and other on your page
fastdom.measure(() => {
const h = el.offsetHeight;
fastdom.mutate(() => {
other.style.height = h + 'px';
});
});
Its costs come from the same design. It works only if all DOM reads and writes go through it, and its strict mode throws on reads outside a measure job during development. Jobs run a frame later, so the element may be gone by then. In its source, a measure scheduled inside a mutate waits for one more frame, so each read-after-write step costs a frame.
requestAnimationFrame does not reorder reads and writes
Moving the loop into requestAnimationFrame looks like a fix, because the callback runs right before the frame’s own layout. It changes when the code runs and leaves the order of reads and writes as it was. Paste this into the console of the test page:
reset();
requestAnimationFrame(() => {
const t = performance.now();
interleaved();
console.log('inside rAF:', (performance.now() - t).toFixed(1), 'ms');
});
In the same Chromium 156 run, the interleaved loop inside requestAnimationFrame took 344.6 ms, as slow as outside it. The Firefox docs warn that reading size or position in a requestAnimationFrame callback often causes a synchronous reflow (Firefox docs). Other callbacks and events in the same frame may already have written.
A read at the start of a callback is cheap only if nothing has written since the last frame. Even then, moving work into requestAnimationFrame delays it until the next frame, and most browsers pause these callbacks in background tabs (MDN).
ResizeObserver reads sizes from the frame’s own layout
Instead of reading a size right after you change something, let the browser report it after its own layout:
// Excerpt: el and label are elements on your page
const ro = new ResizeObserver(entries => {
for (const entry of entries) {
const h = entry.borderBoxSize[0].blockSize; // no layout query
label.textContent = Math.round(h) + 'px';
}
});
ro.observe(el, { box: 'border-box' });
The callbacks run inside update the rendering, right after style and layout (HTML). Each entry holds sizes copied from that layout, so reading entry.borderBoxSize is a property read on a plain object and forces nothing (Resize Observer spec). In Chromium, a forced layout from offsetHeight never fires these callbacks; they run only as part of a frame.
ResizeObserver has four limits:
- Size only: entries carry no position, and CSS transforms do not trigger a callback.
- A second layout: the write to
labelin the callback makes the browser run style and layout again in the same frame, before paint. You avoid a forced layout but still pay for another layout pass. - Loops: if callbacks keep changing observed sizes, the browser stops at a depth limit and moves the rest to the next frame. It then reports the error “ResizeObserver loop completed with undelivered notifications.” MDN notes that users may see a flash of broken layout (MDN).
- Timing: callbacks come after layout, so they cannot give you a size synchronously inside a click handler.
IntersectionObserver reports position at thresholds
For position, IntersectionObserver gives you the element’s box relative to a root, computed in the frame after layout. Its spec names the problem it replaces, which is position code built on DOM queries that cause style recalculation and layout (Intersection Observer spec).
// Excerpt: sentinel is an element near the end of a list; loadMore is your function
new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) loadMore();
}, { rootMargin: '200px' }).observe(sentinel);
Each entry also carries boundingClientRect, so you do not need to call getBoundingClientRect(). The cost is precision. It reports only when the target crosses a threshold, and the callbacks arrive later, in a separate task. It is a visibility signal and does not track position continuously.
CSS that sizes elements without a measuring script
Some scripts measure an element only to set a size that CSS can now compute itself:
.card-wrap { container-type: inline-size; }
@container (width > 40rem) { .card { display: grid; } }
textarea { field-sizing: content; }
:root { interpolate-size: allow-keywords; }
.drawer { height: 0; overflow: clip; transition: height .3s; }
.drawer.open { height: auto; }
- Container size queries (
container-typeand@container) replace a ResizeObserver that adds a class at a certain width. They are Baseline widely available since August 2025. The cost is thatcontainer-type: inline-sizeapplies layout, style and inline-size containment, so the container’s width cannot come from its content (MDN). field-sizing: contentreplaces setting a<textarea>height fromscrollHeighton every key press, which is a read after a write each time. It is Baseline newly available since June 16, 2026. Older browsers show a fixed-size field (MDN).interpolate-size: allow-keywordsreplaces measuringscrollHeightto animate a height toauto. It works only in Chromium browsers (Chrome 129 and later), and other browsers jump to the end without animating (MDN). Becauseheightaffects layout, layout still runs on every animation frame; the property removes the JavaScript read and leaves the layout.
CSS that positions or skips content without a measuring script
Two more features replace reads of position, or skip work that reads would otherwise trigger:
.trigger { anchor-name: --tip; }
.tip {
position: absolute;
position-anchor: --tip;
position-area: top;
position-try-fallbacks: flip-block;
}
.feed > article { content-visibility: auto; contain-intrinsic-size: auto 400px; }
- Anchor positioning replaces calling
getBoundingClientRect()on a trigger, plus scroll and resize listeners, to place a tooltip. The core properties work in all three engines since Firefox 147 in January 2026. The cost is thatposition-visibility: anchor-visibleandanchor-validwork only in Chrome 157 and Safari 27, and older Firefox versions need a JavaScript fallback (MDN). content-visibility: autoskips style, layout and paint for content far off screen.contain-intrinsic-sizegives the skipped content a placeholder size, so the scrollbar stays stable. It is Baseline newly available since September 15, 2025 (web-features data). The cost is that a script that reads layout inside skipped content forces that content to be laid out, so the work moves to the read (CSS Containment 2).
Tools that find forced layouts, and what changed since 2024
The Long Animation Frames API (LoAF) reports animation frames that took a long time, with an entry for each script that ran in them. Each script entry has forcedStyleAndLayoutDuration, the time that script spent in forced style and layout (LoAF spec). Paste this into the console of the test page:
new PerformanceObserver(list => {
for (const frame of list.getEntries()) {
for (const script of frame.scripts) {
console.log(frame.duration, script.duration,
script.forcedStyleAndLayoutDuration, script.forcedLayoutDuration);
}
}
}).observe({ type: 'long-animation-frame' });
reset();
setTimeout(interleaved);
In the Chromium 156 run, the interleaved loop produced a 358 ms frame. Its script entry lasted 355 ms, and forcedStyleAndLayoutDuration was 184 ms of that. forcedLayoutDuration was undefined, because Chromium 156 does not have the split fields yet.
The cost of LoAF is its reach, because only Chromium browsers (Chrome and Edge 123 and later) support it. Firefox and Safari users send no data.
The Forced reflow insight is an entry in the Insights tab of the DevTools Performance panel. It lists the call frames that triggered forced layouts, the top function call and the total time (Chrome for Developers). Its docs say to have no forced reflow over 30 ms. The DevTools code adds up all forced style and layout time in one task and flags the task at 30 ms or more (WarningsHandler.ts).
Under that rule, 100 forced layouts of 0.5 ms each in one task get flagged. Its limit is that it sees only the traces you record on your own machine.
What changed, by date:
- March 12, 2024: INP replaced First Input Delay as a Core Web Vital (web.dev).
- March 2024, Chrome 123: the Long Animation Frames API shipped (Chrome for Developers).
- March 2025, Chrome 134: DevTools added the Forced reflow insight to the Performance panel (What’s new in DevTools 134).
- Late 2026: separate
forcedStyleDurationandforcedLayoutDurationfields ship in Chrome [Chrome version that ships forcedStyleDuration and forcedLayoutDuration] (chromestatus).
A checklist for a page that freezes after a change
- Record the slow interaction in the Chrome DevTools Performance panel and open the Forced reflow insight. Start with its top function call.
- In the field, observe
long-animation-frameentries and log the script entries with a largeforcedStyleAndLayoutDuration. - In the code they point to, move every layout read before the first write, as
batched()does. - Where code reads a size or a position after the browser has laid out, use ResizeObserver or IntersectionObserver entries instead.
- Where code measures only to set a size or position, try the CSS features above.
- For a widget that still forces layouts, give it a fixed size and
contain: strict, so each layout stays inside it.
Next, record the test page’s interleaved loop in the DevTools Performance panel, then open the Forced reflow insight and the Layout events under it.
Primary sources for further reading:
- The HTML Living Standard’s update the rendering steps
- CSSOM View for
offsetHeightand CSSOM resolved values forgetComputedStyle() - The Resize Observer spec and the Long Animation Frames spec
- Blink source at one pinned commit:
offsetHeightForBinding(),Document::UpdateStyleAndLayout(),MarkContainerChainForLayout()andObjectIsRelayoutBoundary() - Chrome’s Forced reflow documentation
Subscribe to the Stay Online newsletter to get the next part of this series.
Comments
No comments yet. Ask a question or share what worked for you.