How Browsers Actually Paint Pixels (And Why Your Page Janks)
Inside the browser's rendering pipeline—from DOM and CSSOM to Layout, Paint, and GPU Compositing—and how to eliminate layout thrashing and 60fps animation jank.
You'll learn the exact five-stage pipeline a browser runs to turn HTML, CSS, and JavaScript into pixels on your monitor, why animating top or width wrecks frame rates while transform and opacity stay at 60–120fps, and how to spot and eliminate forced synchronous layouts. Assumes comfort with HTML, CSS, and DOM manipulation.
1. The 16.6-millisecond budget
Your laptop screen probably refreshes 60 times a second (or 120 times on modern displays). That gives the browser 16.6 milliseconds per frame—about 8.3ms at 120Hz—to run your JavaScript, recalculate styles, figure out where every box sits, paint the pixels, and hand the finished frame to the GPU.
If any single frame takes 35ms instead of 16ms, the screen misses its refresh deadline and shows the old frame twice. Your user perceives that as a stutter—or, as browser engineers politely call it, jank.
To stop guessing why an animation stutters, you need to know what the browser actually does inside those 16 milliseconds. Every visual update flows through a five-stage assembly line called the pixel pipeline:
JavaScript / CSS -> Style -> Layout -> Paint -> CompositeNot every change triggers every stage. And that single fact is the secret to fast web interfaces.
2. Stage 1 & 2: DOM, CSSOM, and Style Calculation
When the browser downloads your page, it parses HTML bytes into a tree of objects called the DOM (Document Object Model), and parses CSS bytes into a second tree called the CSSOM (CSS Object Model).
Neither tree alone is enough to draw anything:
- The DOM knows what elements exist (
<p>,<button>), not what color they are. - The CSSOM knows what rules exist (
.btn { color: pink; }), not which elements are on the page.
During the Style stage, the browser walks the DOM and matches every element against your CSS selectors to compute its final resolved styles (color: #ff2e88, font-size: 16px, etc.).
Why selector simplicity matters (a little): Browsers match selectors right-to-left. On .nav ul li a, the browser first finds every <a> on the page, then walks upward checking if it sits inside an <li>, then a <ul>, then .nav. Deep descendant chains don't usually blow up your budget on small pages, but on a page with 10,000 DOM nodes, a flat single-class selector like .nav-link skips all that upward tree-walking.
The output of DOM + Style is the Render Tree: only the visible nodes (skipping <head>, <script>, and anything with display: none). Note that visibility: hidden is in the Render Tree because it still reserves blank space on the page, whereas display: none is omitted completely.
3. Stage 3: Layout (Reflow) — the expensive one
Once the browser knows what is visible and what styles apply, it runs Layout (also called Reflow). Layout is geometry: the browser calculates the exact x, y, width, and height of every box on the screen, in pixels, relative to the viewport.
Here is why Layout is dangerous: boxes depend on each other.
If you change the font-size or width of one element near the top of the page, its height might grow by 14 pixels. That pushes down the paragraph below it, which pushes down the card grid below that, which changes the total page height, which might cause a vertical scrollbar to appear—which narrows the viewport by 15 pixels and forces every percentage-width box on the entire page to recalculate!
Changing any geometric property triggers Layout:
width,height,min-heightpadding,margin,border-widthtop,left,right,bottomfont-size,line-height,display
When a tutorial tells you "don't animate left or width", this is why: changing left by 1px on every animation frame forces the browser to re-run Layout 60 times a second.
Open Chrome/Edge DevTools -> Performance tab, record 2 seconds of scrolling or clicking on a heavy site, and look for purple bars labeled Layout. Those bars are geometry recalculations.
4. Stage 4: Paint — filling in pixels
After Layout knows where every box sits, Paint (rasterization) fills in the visual details inside those boxes: text glyphs, background colors, borders, rounded corners, gradients, and box shadows.
Paint does not usually happen directly onto one giant bitmap. Instead, the browser records a list of draw calls ("draw rectangle at (0,0), draw text 'Hello' at (16,20)") and rasterizes tiles into memory.
Changing visual-only properties skips Layout completely and jumps straight to Paint:
color,background-colorborder-color,box-shadowvisibility
Skipping Layout is better, but Paint can still be surprisingly slow—especially large blurred box-shadows, backdrop-filter: blur(...) over moving content, or complex SVG filters.
5. Stage 5: Composite — the GPU fast lane
To avoid repainting the whole page whenever one menu slides open, the browser splits parts of the page into separate compositor layers (think of clear overhead projector transparencies stacked on top of each other).
During the Composite stage, the GPU takes those already-painted layers and combines them into the final image on your screen.
Here is the superpower: if a layer is already painted in GPU memory, the GPU can move, scale, rotate, or fade that entire transparency sheet in under a millisecond—without running Layout and without running Paint!
Only two families of CSS properties run purely on the Compositor (when promoted cleanly):
transform(translateX,translateY,scale,rotate)opacity
Compare two ways to slide a drawer 300px to the right:
/* Slow: triggers Layout + Paint + Composite on every frame */
.drawer-slow {
position: fixed;
left: -300px;
transition: left 0.3s ease;
}
.drawer-slow.open {
left: 0;
}
/* Fast: runs strictly on the GPU Compositor */
.drawer-fast {
position: fixed;
left: 0;
transform: translateX(-100%);
transition: transform 0.3s ease;
}
.drawer-fast.open {
transform: translateX(0);
}Both look identical to the user when things are idle. On a mid-range phone, .drawer-slow drops frames while .drawer-fast glides at a locked 60–120fps.
Don't promote everything with will-change
You may see advice to slap will-change: transform on everything. Resist that urge. Promoting an element to its own compositor layer allocates real GPU memory (VRAM) for its bitmap. Promote 500 cards to layers on a phone and you can crash the browser tab with an out-of-memory error. Use will-change sparingly—only on elements you are actually about to animate—and remove it if it is not needed.
Animate transform and opacity whenever humanly possible. Every time you animate top, left, width, height, or margin, you are paying for Layout + Paint on every single frame.
6. Layout Thrashing: the silent JavaScript killer
Even if you never animate geometric properties in CSS, JavaScript can accidentally force the browser to run Layout dozens of times inside a single frame. This bug is called Forced Synchronous Layout (or layout thrashing).
Normally, browsers are lazy in a smart way: if your JavaScript changes box.style.height = "200px", the browser queues that change and waits until the end of the frame to run Layout once.
Unless you ask JavaScript for a measurement.
The moment you read a geometric property—like el.offsetHeight, el.offsetWidth, el.getBoundingClientRect(), or window.getComputedStyle(el)—the browser cannot give you an accurate answer using stale layout data. So it stops everything, forces Layout right now, hands you the number, and continues.
Now watch what happens inside a loop:
// BAD: Layout thrashing (Read -> Write -> Read -> Write in a loop)
const cards = document.querySelectorAll(".card");
for (const card of cards) {
const height = card.offsetHeight; // Forces Layout!
card.style.height = `${height + 20}px`; // Invalidates Layout!
}With 100 cards, that tiny loop forces 100 full-page Layout passes inside one frame.
The fix is dead simple: batch all your reads first, then batch all your writes:
// GOOD: 1 Layout read pass, then 1 queued write pass
const cards = [...document.querySelectorAll(".card")];
// 1. Read phase (Layout is clean, calculated once)
const heights = cards.map((card) => card.offsetHeight);
// 2. Write phase (all mutations queued for the end of the frame)
cards.forEach((card, i) => {
card.style.height = `${heights[i] + 20}px`;
});Same result. 99 fewer Layout passes.
Audit any animation or scroll handler you write: if it reads getBoundingClientRect() or offsetTop after setting .style.*, reorder it so all reads happen before all writes.
7. Skipping off-screen work with content-visibility
On long tutorial or documentation pages (hundreds of paragraphs, code blocks, and tables), the browser still spends time running Layout and Paint on sections 8,000 pixels below the fold that the user hasn't even scrolled to yet.
Modern CSS gives you a one-line escape hatch: content-visibility: auto.
.tutorial-section {
content-visibility: auto;
contain-intrinsic-size: auto 600px;
}content-visibility: autotells the browser: "If this section is far off-screen, skip Layout and Paint for its contents until the user scrolls near it."contain-intrinsic-size: auto 600pxgives the browser an estimated placeholder height (600px) so the page scrollbar doesn't jump wildly as sections come into view, whileautoremembers the real measured height once a section has been rendered.
On long content pages, this alone can cut initial rendering work in half.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Animating top / left / width | Triggers Layout + Paint on every frame (jank) | Animate transform: translate(...) / scale(...) instead |
Reading offsetHeight after setting .style in a loop | Forces Synchronous Layout on every iteration | Batch all DOM reads first, then all DOM writes |
Adding will-change: transform to * or 100s of items | Exhausts GPU memory and slows compositing | Only apply will-change to the few elements actively animating |
Heavy backdrop-filter: blur() over scrolling video/3D | Forces expensive GPU repaints every frame | Keep blurred surfaces small, static, or use solid translucent rgba() |
Missing contain-intrinsic-size with content-visibility: auto | Scrollbar jumps because off-screen sections report 0px height | Pair with contain-intrinsic-size: auto <estimate>px |
Practice
Analyze each snippet before checking the answers.
Exercise 1. Which stages of the pixel pipeline (Style -> Layout -> Paint -> Composite) run when you toggle each CSS property?
- Changing
background-colorfrom#07060dto#12101f - Changing
margin-topfrom16pxto32px - Changing
transform: translateX(0)totransform: translateX(40px)
Exercise 2. Why does this scroll handler cause jank even though it uses transform?
window.addEventListener("scroll", () => {
const header = document.querySelector("header");
const top = document.querySelector(".hero").getBoundingClientRect().top;
header.style.transform = `translateY(${Math.max(0, -top * 0.2)}px)`;
});Exercise 3. In a React or vanilla JS component, you need to measure a tooltip's width (tooltip.offsetWidth) right after inserting it into the DOM so you can position it with transform. Why is one read-then-write okay here, while doing it in a loop is bad?
Answers
Exercise 1:
background-color-> Style -> Paint -> Composite (skips Layout because geometry didn't change).margin-top-> Style -> Layout -> Paint -> Composite (full pipeline, because geometry changed).transform-> Style -> Composite (skips both Layout and Paint when on a compositor layer).
Exercise 2: On every single scroll tick, it calls querySelector twice and getBoundingClientRect() synchronously, and runs unfiltered on every scroll event (which can fire faster than requestAnimationFrame). Even worse, if anything else mutated the DOM before this listener ran, getBoundingClientRect() forces a synchronous Layout. Cache the element references outside the listener and throttle updates inside requestAnimationFrame (or better, use CSS scroll-driven animations / Motion's useScroll which batches reads cleanly).
Exercise 3: Doing one read (offsetWidth) followed by one transform write triggers at most a single layout pass for that tooltip. Layout thrashing only explodes when you alternate writes and reads (Write -> Read -> Write -> Read), forcing the browser to throw away and recompute the entire page's geometry repeatedly inside one frame.
What you learned
- You have 16.6ms per frame at 60Hz (8.3ms at 120Hz) to run JS, Style, Layout, Paint, and Composite.
- Layout computes geometry and cascades across neighbors; Paint fills pixels; Composite combines layers on the GPU.
transformandopacitystay on the GPU compositor, skipping Layout and Paint.- Reading geometric DOM properties (
offsetHeight,getBoundingClientRect) right after writing styles causes Forced Synchronous Layout—always batch reads before writes. content-visibility: autolets the browser skip off-screen Layout and Paint on long pages.