Sub topic 14
From DOM and CSSOM to pixels
This chapter covers the last stage of the page load: turning parsed HTML and CSS into pixels. It assumes you know what the DOM is and how the parser builds it from the HTML response. It also assumes you can read basic CSS selectors and have used the browser's developer tools. The chapter on fetching CSS, scripts, images and fonts covered how those files arrive. Here the question is what the browser does once it has them.
The pipeline at a glance
The browser does not draw HTML directly. It runs the document through a series of stages, and each stage produces a data structure that the next stage reads.
The names vary between browsers. Chrome also has a "pre-paint" step and a "layerize" step, and Firefox calls its stages by different names. The model above holds in every major engine.
Building the CSSOM
The CSS Object Model (CSSOM) is a tree of style rules, built from every stylesheet the page uses. These include <link rel="stylesheet"> files, <style> blocks, and the browser's built-in default stylesheet. The browser parses the CSS text into rules, each made of a selector and a set of declarations.
The CSSOM cannot be built incrementally the way the DOM can. A later rule can override an earlier one, so the browser cannot know the final style of any element until it has read all the CSS. For this reason, CSS is render-blocking. The browser will not paint anything until the stylesheets referenced in the <head> are downloaded and parsed.
Consider the example page from earlier in this tutorial:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/style.css">
<script src="/app.js" defer></script>
</head>
<body>
<h1>Hello</h1>
<img src="/logo.png" alt="Logo">
</body>
</html>The parser builds the DOM for <h1> and <img> while /style.css downloads. The browser still waits for /style.css before it paints. Without the wait, users would see unstyled content flash and then jump to the styled version.
Scripts add a second blocking rule. A plain <script src> without defer or async pauses the HTML parser. That script may also need to wait for pending stylesheets, because it could read computed styles. The defer attribute in the example avoids this: the script downloads in parallel and runs after parsing finishes.
Style calculation
Once the DOM and CSSOM exist, the browser works out the computed style of every element. For each element it does the following:
- Finds all rules whose selectors match.
- Sorts the matching declarations by origin, specificity, and source order.
- Applies inheritance for properties such as
colorandfont-family. - Resolves relative values to absolute ones. For example,
2embecomes pixels andboldbecomes700.
The result is a full set of property values for each element, including properties you never wrote. The DevTools Computed tab shows this result.
Elements with display: none receive computed styles, but they do not appear in the render tree.
The render tree
The render tree (Chrome calls its version the layout tree) combines the DOM with the computed styles. It contains only what will be displayed.
- Elements with
display: noneare left out, along with their descendants. - Elements with
visibility: hiddenstay in the tree, because they still take up space. <head>,<script>and<meta>elements are left out because they have no visual output.- Pseudo-elements such as
::beforeare included, even though they do not exist in the DOM. - Text is split into separate boxes where the browser needs to wrap it.
Layout
Layout (also called reflow) calculates the size and position of each box. The browser starts at the root with the viewport width and works down the tree. A block element takes the width of its container, and its height depends on its content. Percentage widths, flexbox, grid, floats and text wrapping all feed into this calculation.
Layout is expensive for two reasons. First, one change can affect many boxes. Widening a container changes how its text wraps, which changes its height, which pushes down every sibling after it. Second, the browser must complete layout before it can paint, so a slow layout delays what the user sees.
The output of layout is a set of exact geometry values for each box, in pixels. These are the values getBoundingClientRect() returns.
Paint
Paint converts boxes into drawing instructions. The browser produces a list of operations, such as "fill this rectangle with this color", "draw this text at this position", and "draw this image here". The order of the list follows stacking rules: backgrounds first, then borders, then content, with z-index deciding which stacking contexts go on top.
Paint at this stage records instructions. The browser then rasterizes the instructions, meaning it turns them into actual pixels. In modern browsers rasterization often runs on the GPU and on separate threads.
Compositing
Browsers often split a page into layers. Each layer is painted and rasterized on its own, and the compositor then assembles them in the right order into the final frame. Elements are promoted to their own layer when they use things like transform or opacity animations, will-change, <video>, or <canvas>.
Layers matter because the compositor can move, fade, or scale an existing layer without re-running layout or paint. Scrolling works the same way: the browser scrolls a prepainted layer instead of repainting the page. The compositor typically runs on its own thread, so these updates stay smooth even when the main thread is busy running JavaScript.
Which changes cost what
The cost of a change depends on how early in the pipeline it forces the browser to start over.
| Change | Restarts at | Cost |
|---|---|---|
| `width`, `height`, `margin`, `top`, font size | Layout, then paint and compositing | High |
| `color`, `background-color`, `box-shadow` | Paint, then compositing | Medium |
| `transform`, `opacity` (on a layer) | Compositing only | Low |
So animating left forces layout on every frame, and animating transform: translateX() often does not. Browser-specific details differ, and the site [CSS Triggers](https://csstriggers.com) used to catalog them, but you should verify in DevTools instead of assuming.
/* Forces layout on every frame */
.slide-bad { position: relative; transition: left 300ms; }
.slide-bad.open { left: 200px; }
/* Usually compositor-only */
.slide-good { transition: transform 300ms; }
.slide-good.open { transform: translateX(200px); }Forced synchronous layout
Browsers normally batch layout work and run it once per frame. Reading a geometry property such as offsetWidth, clientHeight or getBoundingClientRect() after a style change forces the browser to run layout immediately, so that the value it returns is correct. Doing that in a loop is called layout thrashing.
const boxes = document.querySelectorAll('.box');
// Slow: each iteration reads (forcing layout) after the previous write
function growSlow() {
for (const box of boxes) {
const w = box.offsetWidth;
box.style.width = (w + 10) + 'px';
}
}
// Better: do all reads first, then all writes
function growFast() {
const widths = Array.from(boxes, (b) => b.offsetWidth);
boxes.forEach((b, i) => {
b.style.width = (widths[i] + 10) + 'px';
});
}growFast triggers layout once for the reads, then the writes queue up and the browser lays out once more for the next frame.
First paint and what users perceive
The first time the browser paints anything is First Paint. First Contentful Paint (FCP) is the first paint of real content, such as text or an image. Largest Contentful Paint (LCP) marks when the biggest visible element has rendered. LCP is the most common measure of "the page looks loaded".
A slow FCP usually traces back to earlier chapters: a slow server response, a render-blocking stylesheet, or a synchronous script in the <head>. You can read these values in the browser:
for (const type of ['paint', 'largest-contentful-paint']) {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.entryType, entry.name || '', Math.round(entry.startTime), 'ms');
}
}).observe({ type, buffered: true });
}Common errors
- Expecting
display: noneto keep layout space. It removes the element from the render tree. Usevisibility: hiddento keep the space. - Putting a large stylesheet at the end of the body. Late CSS can cause a flash of unstyled content, and it can trigger a second layout.
- Adding
will-changeeverywhere. Each layer uses GPU memory, and too many layers slow down compositing. - Missing image dimensions. An
<img>withoutwidthandheighthas no known size until it loads. The page layout then shifts, which hurts the Cumulative Layout Shift metric. - Treating the stages as strictly one-time. The pipeline runs again whenever the DOM or styles change. A single page load triggers many layouts and paints.
Observing the pipeline
In Chrome DevTools, open the Performance panel, record a page load, and look at the main thread. Purple blocks are Layout and Recalculate Style. Green blocks are Paint and Composite. The Rendering drawer (under More tools) has "Paint flashing", which highlights repainted regions, and "Layout Shift Regions". The Layers panel shows how the page splits into compositor layers.
Exercise
A page's stylesheet is linked in the head and takes 800 ms to download. The HTML arrives in 100 ms and the DOM is built almost immediately. When can the browser first paint the page content, and why? What would change if the same CSS were loaded by a script that runs after the page has loaded?
Show answer
The first paint waits for the stylesheet, so it happens after about 800 ms, because CSS is render-blocking and the CSSOM must be complete before the browser can compute styles. If the CSS were added later by script, the browser could paint the unstyled content sooner, but users would see a flash of unstyled content followed by a restyle and a new layout when the CSS arrives.
Exercise
You need to move a menu 300 px to the right with an animation. Compare animating left with animating transform: translateX(300px). Which pipeline stages run on each frame, and which option do you pick?
Show answer
Animating left changes geometry, so every frame needs style calculation, layout, paint and compositing. Animating transform on a promoted layer usually needs only compositing, because the layer is already painted and the compositor can just move it. Pick transform, then confirm in the Performance panel that no Layout blocks appear in the animation frames.