Skip to content

The DOM, layout and paint

Working knowledgeUnder the hood

A page goes from HTML text to a tree of nodes, then to a tree of boxes with sizes, then to pixels. Each stage feeds the next, so a change to the page re-runs some of them and not others. Here is each stage drawn on one small page, and which changes cost what.

01 The page

A tiny shop page: a heading, a hidden promo line and a cart with two items. The CSS sets fixed sizes so you can follow the layout arithmetic exactly.

index.html
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>Shop</h1>
<p class="promo">Free delivery</p>
<ul class="cart">
<li>Tea</li>
<li>Mugs</li>
</ul>
</body>
</html>
app.css
body { margin: 0; width: 400px; }
h1 { margin: 0; height: 40px; }
.promo { display: none; }
.cart { margin: 0; padding: 10px; }
li { height: 30px; }

02 HTML becomes the DOM

The HTML parser reads the text as a stream of tags and builds the DOM: a tree of objects, one per element, that JavaScript can read and change. It builds it as the bytes arrive, without waiting for the whole file.

Parsing index.html
Step 1 of 10
DOMEmpty
  • node just created
  • already in the DOM

The bytes of index.html have started to arrive. The tokenizer has not produced any tags yet, so the DOM is empty.

0 nodes

03 Not every node gets a box

Next comes style: the browser matches each CSS rule against the DOM and works out a computed value for every property of every element. From those values it builds a second tree, the layout tree (also called the box tree or render tree). Only elements that are displayed get a box.

Which DOM nodes get a box
DOM, marked by whether it gets a box
html
head
linkapp.css
body
h1Shop
p.promo
ul.cart
liTea
liMugs
  • gets a box
  • no box

head and link are display: none in every browser’s default stylesheet. p.promo is display: none because of app.css. It is still in the DOM, so document.querySelector(".promo") finds it, but it takes no space and is never painted.

04 Layout: sizes and positions

Layout (also called reflow) walks the box tree and gives every box an x, y, width and height. For normal block boxes the rule is simple: a box’s width comes from its parent, and its height comes from its children. So widths are known on the way down and heights only on the way back up.

Laying out the page
Step 1 of 8
Layout results (px)
xywh
body
h1
ul.cart
li Tea
li Mugs
  • just worked out
  • waiting on children
  • last value settled
  • not reached yet

Layout starts at the top of the box tree with the viewport, 800 px wide. No box has a size or position yet.

800 px wide viewport

You can read these numbers back: in the browser console, document.querySelector(".cart").getBoundingClientRect() returns x: 0, y: 40, width: 400, height: 80, the border box the trace ended with.

05 Paint and composite

Paint turns the laid-out boxes into a list of drawing commands, in the order they stack. It does not touch pixels yet.

What paint records
Display list for the page (simplified)
fill rect 0,0 800×600 whitetext "Shop" in h1 boxbullet at li Teatext "Tea" in li boxbullet at li Mugstext "Mugs" in li box

Real display lists hold many more entries: borders, backgrounds and text runs for each box.

Then the commands are rasterised into pixels, typically in tiles and often on the GPU. Some parts of the page are painted into separate layers, for example an element with an animated transform or opacity. The compositor places the layers on top of each other to make the frame. Moving or fading a layer only needs a new composite, not a new paint.

06 What each change re-runs

The stages run in order, so a change re-runs the first stage it affects and everything after it. Browsers mark only the affected parts as dirty and redo as little as they can, but the order is fixed.

Typical cost of a change in current Chrome, Firefox and Safari
ChangeStyleLayoutPaintComposite
width, height, padding, font-sizeyesyesyesyes
add or remove an elementyesyesyesyes
display: noneyesyesyesyes
color, background-coloryesnoyesyes
visibility: hiddenyesnoyesyes
transform, opacity (own layer)yesnonoyes
el.style.widthLayout + paintEvery box after it may move, so positions are recalculated and the area repainted.
el.style.backgroundColorPaint onlyNothing moves, so layout is skipped, but the pixels of that box are drawn again.
el.style.transformComposite onlyOn its own layer, the already-painted pixels are just moved by the compositor.

visibility: hidden keeps the element’s box, so nothing around it moves. display: none removes the box, so everything after it is laid out again.

07 Forcing layout from JavaScript

When your script changes a style, the browser does not lay out straight away. It waits and does it once before the next frame. But if your script then reads a geometry value such as offsetWidth, getBoundingClientRect() or scrollTop, the browser must run layout immediately to give a correct answer. Alternate writes and reads in a loop and you get one full layout per pass.

Read, write, read, write
const boxes = [...document.querySelectorAll(".box")];
for (const b of boxes) {
// each read forces layout, because the
// previous write made it stale
b.style.width = b.offsetWidth + 10 + "px";
}
Reads first, then writes
const boxes = [...document.querySelectorAll(".box")];
const widths = boxes.map((b) => b.offsetWidth);
boxes.forEach((b, i) => {
b.style.width = widths[i] + 10 + "px";
});
// one layout, before the next frame

This is called layout thrashing. In Chrome DevTools, record in the Performance panel: forced layouts show up as purple Layout blocks inside your script’s task, marked with a forced reflow warning.

08 When it bites

@keyframes slide { to { left: 300px; } }Animating layout propertiesChanging left, top, width or margin every frame runs layout and paint every frame. Animate transform: translateX(300px) instead, which the compositor can handle alone.
* { will-change: transform; }Too many layersEach layer costs memory for its pixels, and too many make compositing slower. Promote only the elements you are actually animating.
list.innerHTML += "<li>Tea</li>";Rebuilding the DOM+= on innerHTML reparses and recreates every existing child, so style and layout run for all of them. Use append() or insertAdjacentHTML() to add only the new node.
document.querySelectorAll("*").length // 20000A very large DOMStyle and layout scale with the number of elements they touch. A change near the root of a huge tree can be slow even when only one property changed.

09 Check yourself

Question

A button’s background-color changes on hover. Which stages run again?

Question

In the layout trace, why was the height of ul.cart the last thing settled before body’s?

Question

You set el.style.width = "300px" and on the next line read el.offsetWidth. What happens?

10 Practise this

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