Web and networkingDive 11 of 12
How HTML becomes pixels
One product card, from arriving bytes to a glowing display. Build its DOM, resolve its CSS, and find out why moving a badge can cost a frame.
- Levels
- 9
- Reading
- 42 min
- Depth
- Idea to Silicon
- Published
One card. Four representations.
A click changes a tree.
You see new pixels.
Put the Field notebook in your cart. Follow the same state through the browser’s working representations.
Source + state
<article class="card">
<h2>Field notebook</h2>
<button aria-pressed="false">
Add to cart
</button>
<span class="badge">0</span>
</article>Initial HTML plus the current script state.
DOM nodes
- article.card
- h2 → “Field notebook”
- button
- “Add to cart”
- span.badge → 0
Layout boxes
Box sketch; rendered card content box: dimensions measured by your browser.
Composited result
Field notebook
Plain pages. Room to think.
€12Content plane + movable badge plane (schematic).
The cart is empty. The button changes text and state; the badge moves with a transform.
A deadline every few milliseconds
You click Add to cart
on a notebook. The label changes, a counter becomes 1, and a little badge lifts away from the corner of the card. Nothing about the request sounds expensive. A few characters changed. One small rectangle moved eight pixels. Yet the same interaction can feel immediate on one page and sticky on another.
The browser has two jobs here. It must determine what the page now means, then turn that meaning into an image before the display needs another one. The first job involves HTML, CSS and JavaScript. The second involves geometry, drawing commands, memory, several threads and eventually a display controller. A tiny edit near the start can invalidate a surprising amount of work downstream.
A 60 Hz display starts a new refresh about every 16.67 milliseconds. At 120 Hz, the interval is about 8.33 ms. These are deadlines, not a JavaScript allowance. Input handling, rendering preparation, rasterization, communication between threads and presentation all share the available time. Your handler may begin halfway through an interval, with only a fraction of it left.
Visible irregularity in motion or response, often because an image stays on screen longer than intended when the next update misses its presentation deadline. is the irregular rhythm you see when updates miss those deadlines. The display can show the previous image again, so an object that should move equal distances on successive refreshes instead pauses and jumps. A steady 30 frames per second on a 60 Hz panel may look less smooth than 60; irregularly alternating intervals can feel worse still. Change the refresh rate below while keeping the same work.
16.67 ms between refreshes. 10 ms of work leaves 6.67 ms before this model’s deadline.
Linear 0–40 ms scale. Work starts at a refresh boundary; raster, presentation and scheduling also need time.
Five questions between a document and a picture
The usual pipeline is parse, style, layout, paint, composite. Each stage answers a different question. Parsing asks which nodes exist. Style asks which properties apply to those nodes. Layout asks how big the boxes are and where they go. Paint records how to draw them, in the right order. Compositing assembles drawable surfaces into the image that will be presented.
This is a dependency graph rather than a compulsory five-stop journey on every frame. Changing a text node can affect line breaks and require fresh layout. Changing a background color can reuse geometry but require fresh painting. Moving already-rasterized content with an eligible transform animation can reuse both geometry and drawing. The fastest update is often the one that starts furthest down this graph.
DOM, CSS and JavaScript share this thread.
Can reuse the last committed content.
Raster tasks turn instructions into image tiles.
Combines page content and other surfaces.
Those thread and process names are Chromium terms. Firefox’s WebRender and WebKit’s rendering and compositing machinery arrange the work differently. The standards specify observable behavior, not a required process architecture. Chromium itself also has software and platform-dependent paths. Its cc architecture document explains the separation between producing painted inputs, rasterizing resources and forwarding compositor frames.
We will keep one small page throughout: the Field notebook card. The button changes text and an accessibility state; the badge changes content and position. That distinction matters: moving a badge can be cheap, while replacing its text still creates new content to draw. Here is the complete example, with only the CSS needed to identify those changes.
<!doctype html>
<meta charset="utf-8">
<title>Field supplies</title>
<style>
.card {
width: min(24rem, 100%);
position: relative;
}
.badge {
position: absolute;
top: 0;
right: 0;
transition: transform 250ms;
}
@media (prefers-reduced-motion: reduce) {
.badge { transition: none; }
}
.card[data-added] .badge { transform: translateY(-8px); }
</style>
<article class="card">
<h2>Field notebook</h2>
<p>Plain pages. Room to think.</p>
<button aria-pressed="false">Add to cart</button>
<span class="badge">0</span>
</article>
<script>
const card = document.querySelector(".card");
const button = card.querySelector("button");
button.addEventListener("click", () => {
const added = button.getAttribute("aria-pressed") !== "true";
button.setAttribute("aria-pressed", String(added));
button.textContent = added ? "Added to cart" : "Add to cart";
card.querySelector(".badge").textContent = added ? "1" : "0";
card.toggleAttribute("data-added", added);
});
</script>A frame is a deadline shared by several kinds of work. The cost of a change depends on which earlier results it invalidates.
Bytes become characters, characters become tokens
The network does not deliver angle brackets or elements. It delivers bytes, usually in chunks that end wherever transport and buffering happen to put the boundary. Before an HTML parser can recognize <article>, the browser must choose an encoding and decode those bytes into characters. Even an apparently simple character such as the euro sign in our price can occupy several bytes.
For ordinary network-loaded HTML, the HTML encoding-sniffing algorithm gives a byte order mark precedence over a transport encoding label. A Content-Type: text/html; charset=utf-8 header supplies that transport label. If those have not settled the choice, the browser can prescan the beginning of the input for a metadata declaration such as <meta charset="utf-8">. The declaration must be entirely within the first 1024 bytes under the HTML authoring requirements.
The algorithm has additional paths for user overrides, inherited hints and implementation defaults. The practical rule is pleasantly small: serve an explicit UTF-8 header, save the file as UTF-8, and put the matching meta declaration near the beginning. Do not rely on a late declaration to rescue already-decoded content. A tentative decoder can sometimes be restarted when the parser discovers a declaration; an encoding already chosen with certainty is not simply overwritten by any later tag.
- Optional UTF-8 BOM
- <p>
- €
- 12</p>
A state machine, not a regular-expression replacement
After decoding, the input stream preprocesses CRLF and lone CR into LF. The tokenizer then consumes characters according to a current state. In the data state, ordinary text emits character tokens. A less-than sign switches to tag open. An ASCII letter there begins a start-tag token; a slash leads toward an end tag. In tag name, ASCII capitals become lowercase, whitespace begins attribute processing, and a greater-than sign emits the token.
The same greater-than sign means something different inside a quoted attribute value. In <p title="a>b">, the first one belongs to the title. Only the one after the closing quote ends the tag. Likewise, a slash in an unquoted attribute value is part of that value: <div title=notes/> gives the title notes/, rather than setting a self-closing flag. The tokenizer needs its state to distinguish these cases.
An ampersand branches into character-reference processing, which returns decoded characters to the previous context. & contributes one ampersand to a text token or an attribute value. It does not create a nested HTML parse. A decoded less-than sign from < is text, not a new tag opener. The tokenizer does not feed emitted characters back through the data state.
Try editing the input. Quoted greater-than signs, duplicate attributes and unfinished tags are useful probes. Move the inspection control one transition at a time: the machine sometimes reconsumes a character in a new state instead of advancing the input. The token output groups adjacent character emissions so that you can read it.
<tag openEmitted tokens · adjacent character tokens grouped
Accepted subset
Data-state HTML with article, div, p, span, h2, button, b, i, em, strong, table, tbody, tr, td and br. ASCII case folding, attributes (quoted or unquoted), duplicate attributes, self-closing flags, EOF recovery, CR preprocessing. References: semicolon-terminated amp, lt, gt, quot, apos and non-control Unicode scalar numbers. No comments, doctype, raw text, foreign content or other named references. Unsupported constructs are rejected.
The complete WHATWG tokenizer has many more states. Inside a script, ordinary text rules would misread less-than signs in JavaScript. A textarea uses RCDATA, where character references still work but most apparent tags are text. A style element uses RAWTEXT. The tree builder tells the tokenizer when to switch into these modes. HTML parsing is a conversation between two machines, rather than a tokenizer that finishes an entire file before a separate tree phase begins.
Errors also have specified outcomes. A duplicate attribute is discarded after the first occurrence; an unfinished start tag at EOF is not emitted as a complete element. These choices help different engines agree on broken pages. That agreement matters for security as well as appearance: a sanitizer and a browser that disagree about where an attribute ends may disagree about whether text is executable.
At this point we have tokens such as “start tag article, attribute class equals card,” not boxes or pixels. Even a self-closing flag is only information on a token. In HTML, writing <div /> does not make div a void element. The next machine decides how tokens become nodes.
The tree you wrote is not the tree you get
A token says that the author wrote a start tag. It does not say where that element belongs. The HTML tree builder keeps a stack of open elements and an The current group of tree-construction rules, such as before html, in head, in body or in table. The mode decides what a token does to the tree.. It applies the rules for that mode, sometimes creates missing elements, sometimes changes modes and reprocesses the same token.
Take a document that starts directly with our article. The parser can create the missing html, head and body elements. They exist in the DOM even though their tags were absent from the source. The DOM Standard’s node tree is the resulting ordered hierarchy of objects: Document, Element, Text and other node types. The HTML Standard supplies the parser rules that construct it.
Paragraphs expose why “push a tag, pop its closing tag” is insufficient. In the in-body insertion mode, a div start tag closes an open p in button scope before inserting the div. If a later p end tag arrives without a p in button scope, the recovery rules insert a p and then close it. The paragraph preset below therefore ends with an empty p. No mysterious DOM mutation after parsing is necessary; this is the prescribed construction process.
Tables use different modes. A tr token arriving directly inside a table can cause the builder to insert a tbody, switch into the table-body rules and reprocess the row token. Text in unexpected table positions can be foster-parented outside the table. This is why a DOM inspector can show nodes at positions a source-text search would never suggest.
Trace: <b><i></b></i>
Open stack: body, b
Active formatting: b
body > bOpen stack: body, b, i
Active formatting: b, i
body > b > iNo furthest block after b.
Pop i and b; remove b from active formatting.
DOM still: body > b > ii is active, but no longer on the open stack.
Remove i from active formatting and return.
Final body: <b><i></i></b>- The in-body rules insert b and add it to the active formatting list.
- i is both an open element and an active formatting element.
- The adoption agency algorithm finds b on the stack, but no special block after it. It pops through b; popping does not remove DOM nodes.
- The next end tag removes the stale formatting entry. There is no reconstruction between these adjacent end tags. Choose “Misnested formatting” above to verify the result in your browser.
Why formatting elements need another list
The adoption agency algorithm handles historical formatting markup such as misnested b and i elements. Alongside the open-element stack, the parser keeps a list of active formatting elements. Those structures answer different questions: which elements are currently open, and which formatting may need reconstruction when more content appears.
For exactly <b><i></b></i>, b has no “furthest block” after it on the stack. Processing the b end tag pops through b and removes its formatting entry. The DOM nodes remain attached. The following i end tag finds i in the active list but absent from the open stack, removes that entry, and returns. The resulting body is <b><i></i></b>. There is no extra i sibling in this exact example.
Insert text after the b end tag and the outcome changes: formatting reconstruction can create a new i for that text. More complicated inputs with a special block invoke the algorithm’s reparenting path. The four-step figure deliberately traces the short case; the editable DOM lab lets the browser handle the full tree-construction consequences of the accepted markup.
When a block really moves
Worked input: <b><p>one</b>two</p>. Stacks omit html. b′ names the newly created node, not an HTML tag name.
Open stack: body, b, p
Active formatting: b
body
b (original)
p
"one"Open stack: body, b, p
Active formatting: b
body
b (original)
p ← furthest block
"one"Open stack: body, b, p (not yet repaired)
Active formatting: b
body
b (original, empty)
p
"one"Open stack: body, p, b′
Active formatting: b′
body
b (original, empty)
p
b′ (new)
"one"Open stack: body, p
Active formatting: empty
body
b (original, empty)
p
b′
"one"Open stack: body
Active formatting: empty
body
b (original, empty)
p
b′
"one"
"two"- The parser has consumed <b><p>one. The paragraph is inside the original b.
- The formatting element is b; p is the furthest block; body is the common ancestor. No intermediate node needs cloning in the inner loop.
- Append the last node, p, to the common ancestor, body. Moving p leaves the original b attached and empty.
- Create b′ from the original formatting element. Move p’s children into b′, then append b′ to p. Replace the formatting-list entry and put b′ after p on the open stack.
- For b′ there is no furthest block. Pop through b′ and remove its active-formatting entry. The repaired DOM stays attached.
- With no active b left, two becomes a text sibling of b′ inside p. The p end tag closes the paragraph.
Choose “Reparent a paragraph” in the DOM lab above to verify the final serialization:<b></b><p><b>one</b>two</p>. This follows the adoption agency algorithm’s furthest-block path.
Scripts interrupt a streaming parser
The card’s final inline script can access the preceding article because those nodes have already been inserted. A classic script encountered by the parser normally executes before parsing continues. An external classic script without async or defer pauses the parser while its source becomes available. Previously encountered stylesheets can also delay execution of parser-blocking scripts, because the script may inspect styles. The browser may therefore know about later bytes without having constructed their nodes yet.
A speculative preload scanner can inspect ahead for resources while the main parser is blocked. It can initiate eligible image, script or stylesheet fetches early. It does not replace the authoritative parser, execute the script or commit an alternative DOM. Speculation can save network time; it cannot resolve what a script that calls document.write will insert.
| Script form | When it executes | Ordering consequence |
|---|---|---|
| Classic, no attributes | When encountered; external source must be ready | Parser waits; earlier blocking stylesheets may matter |
| External classic, async | As soon as ready | Can interrupt parsing; download completion affects order |
| External classic, defer | After parsing, before DOMContentLoaded | Deferred classic scripts preserve document order |
| Module, no async | After parsing and module-graph readiness | Deferred by default; top-level await can delay evaluation completion |
| Module, async | When its graph is ready to evaluate | Does not wait for parsing to finish |
These rules apply to parser-inserted scripts; dynamically inserted scripts have their own scheduling rules. The async and defer attributes have no effect on inline classic scripts. Modules also bring module-scoped bindings and dependency loading. The script element specification defines the distinctions. Choose the execution contract you need instead of treating the attributes as interchangeable performance switches.
Now the article, title, description, button and badge exist as nodes. You could change their text without showing anything: a detached document still has a DOM. To display them, the browser needs properties and geometry, beginning with the CSS rules that compete for each element.
The DOM is the parser’s constructed tree. Implied elements and recovery rules make it more than a transcription of source tags.
One value wins for every property
The notebook’s button has styles even before our stylesheet says anything. A user-agent stylesheet supplies defaults; the user may have preferences or user styles; the page adds author declarations. CSS parsing turns source text into rules and declarations. Invalid syntax is discarded according to CSS error recovery, usually without discarding an entire otherwise usable sheet.
Style calculation starts by finding relevant rules: the selector matches the element, the media or support conditions hold, and the declaration is valid for the property. Then the The ordered procedure that chooses a declaration for each element and property from all applicable declarations. chooses a winner for each property. Specificity is only one comparison within that procedure. A very specific selector cannot overcome a declaration that already won at an earlier stage.
The broad precedence, from weaker to stronger, is normal user-agent declarations, normal user declarations, normal author declarations, animation values, important author declarations, important user declarations, important user-agent declarations, and transition values. Active transitions can therefore sit above important declarations. The reversal for important origins protects user needs: an important user style can override an important site style.
Within an origin, cascade layers provide explicit ordering. For normal declarations, later layers beat earlier layers, and unlayered declarations beat layered ones. For important declarations, that layer ordering reverses: the earliest layer wins, and important unlayered declarations lose to important layered declarations. Importance is attached to a declaration, not to an entire selector or rule.
@layer base, components;
@layer base {
#cart.card { color: sienna; }
}
@layer components {
.card { color: teal; }
}
article { color: steelblue; } /* Unlayered normal wins here. */Three columns, compared from left to right
Specificity is a tuple (a, b, c). Count ID selectors in a; classes, attribute selectors and pseudo-classes in b; type selectors and pseudo-elements in c. Combinators and the universal selector add nothing. Compare the leftmost different column. Eleven classes do not carry into one ID, just as eleven minor version increments do not automatically become the next major version.
The functional pseudo-classes are where intuition often fails. :is(), :not() and :has() contribute the maximum specificity of their selector arguments. They do not add another pseudo-class point on top. :where() and everything inside it contribute zero. :nth-child() adds its own pseudo-class point and, if it has anof selector list, the maximum from that list. The matching branch of :is does not determine its specificity; the most specific valid argument does.
A comma-separated rule is different. Its specificity for a given element is the maximum among the selectors in that list that actually match that element. The calculator reports each standalone selector and the list maximum; a list maximum alone cannot tell you the winner for a particular element. Try :where(#cart).badge, then replace where with is. The ID moves from contributing nothing to deciding the first column.
Standalone selectors, including lists, escapes, namespaces and functional pseudos. Expand CSS nesting (&) first. Syntax support is checked by this browser.
#a, .b { & .c { } } has the same specificity as the example:is(#a, .b) .c: (1, 1, 0), even when the ancestor matches .b. Nesting takes the parent list’s maximum, rather than the specificity of only its matching branch.CSS Nesting: specificity.
Resolve color on <article id="cart" class="card">
All three selectors match. Layers are declared base, components. Later rows have later source order. Change an origin or importance and resolve again.
One light-DOM element, one property, three declaration origins; no transitions, animations, inline styles, scopes, shadow boundaries or revert keywords.
The Selectors Level 4 specificity rules define these exceptions. The Cascade Level 5 sorting order adds details such as encapsulation contexts and element-attached styles. A style attribute has special precedence over selector-mapped declarations of the same origin and importance; it is not an ID selector with an enormous number. Scoped style rules add a proximity comparison in theLevel 6 cascade model before source order breaks a remaining tie.
After the cascade comes defaulting and value processing. If color has no winning specified value, it normally inherits the parent’s computed color. Width normally does not inherit; it falls back through its initial-value rules. Inheritance does not enter a parent’s selector into the child’s specificity contest. A directly specified value on the child wins there even when the inherited value originated from a much more specific parent rule.
A computed value has resolved inheritance and many relative expressions, but it need not be a final length in pixels. A percentage width can remain a percentage until layout knows the containing block. The used value is the value after layout-dependent resolution; actual values can reflect implementation limits and rounding. Also, getComputedStyle exposes resolved values, which are used values for some properties. Its name does not promise a raw dump of the specification’s computed-value stage.
Changing data-added on the card can change which selectors match it or its descendants. Engines track dependencies to avoid recalculating every element’s styles for every mutation. Broad selectors, relational dependencies and inherited properties influence how far invalidation spreads. The resulting styles still do not tell us exactly where a line of text ends. For that, we need layout.
Giving every box a place
Our card’s width is min(24rem, 100%). To turn that into a usable length, the browser needs the font-relative rem size and the width of the card’s containing block. The button’s text then needs shaping and line breaking inside the space it receives. Layout propagates constraints until the browser knows the sizes and positions required to display the content.
The layout structure is related to the DOM but is not the same tree. An element with display: none generates no boxes for itself or its descendants. A pseudo-element can generate a box without being an ordinary DOM child. Anonymous boxes bridge structures that CSS formatting requires but the markup did not explicitly supply. A text node can produce several line fragments, and an element split across lines or pages can produce several fragments.
A A region governed by a set of layout rules, such as block, inline, flex or grid formatting. These rules determine how boxes in that context size and position themselves. gives those boxes rules. In ordinary block layout, blocks progress along the block axis, with details such as margin collapsing. Inline content forms line boxes, with glyph shaping, available break opportunities, bidi reordering and available width determining the fragments. Flex layout distributes space along a main axis, then resolves cross-axis behavior. Grid coordinates tracks and items in two dimensions.
Change the context in the figure. The same three DOM children can stack as blocks, participate as flex items, or occupy grid cells. Then expand the button label. A new label might fit on one line, wrap, enlarge an intrinsic contribution or change the card’s height. There is no rule saying that editing only one node confines layout work to that node.
ResizeObserver will report this card’s content box after layout.
Read after every write, or read once?
Opt-in measurement: 80 width writes in each strategy, split across tasks of four writes. Each chunk stops after 8 ms. Results depend on this device and are not a benchmark.
Ready. Both strategies use the same scratch boxes inside this figure.
Invalidation makes a debt; a read can collect it now
Setting a geometric property marks affected layout results dirty. Browsers usually defer the work so that several writes can be handled together. A later rendering update can then calculate the final geometry once, after the script has finished changing its mind. Merely writing a style is therefore not the same as completing layout on that line of JavaScript.
Now ask for offsetWidth immediately after the write. JavaScript expects an up-to-date integer border-box width, so the browser may have to resolve pending style and layout before returning. That is forced synchronous layout. The cost appears inside the JavaScript task that made the read, even though the work is performed by the rendering engine.
Repeated write/read pairs destroy the browser’s chance to coalesce work. One read flushes the first write, another write dirties the result again, and the next read demands another flush. This is layout thrashing. A cached geometric read can be cheap if nothing relevant changed; the harmful dependency is a read that requires fresh results after a mutation.
// Interleaved: each width read can flush the preceding write.
for (const card of cards) {
card.style.width = "240px";
sizes.push(card.offsetWidth);
}
// Batched: update the boxes, then read their geometry together.
for (const card of cards) card.style.width = "240px";
for (const card of cards) sizes.push(card.offsetWidth);The lab uses a small scratch subtree with the same sort of text as our card. Both strategies make 80 writes. To keep the experiment responsive, it yields between chunks and limits each chunk to four writes or roughly 8 ms of work. The batched path reads once at each chunk’s end; the interleaved path reads after every write. The timer excludes the yields but includes the synchronous work inside each chunk.
That makes it a local demonstration, not a universal speed ratio. Layout caches, CPU power, timer precision and scheduling vary. The batched result can occasionally be slower on a short run because noise exceeds the difference. The useful conclusion is the dependency pattern: grouping writes creates fewer points where JavaScript demands current geometry. Real applications should measure representative trees, text and interactions rather than copying a ratio from someone else’s laptop.
Observe the completed result
ResizeObserver offers a way to respond to size changes after layout has produced them. Its rendering-loop integration gathers and broadcasts active observations as part of a rendering update. The callback receives box-size information, so it can read that information without causing another layout merely to obtain it.
Writing sizes in the observer can require another style/layout pass. If callbacks repeatedly resize what they observe, they can create a feedback loop. The specification limits delivery by depth and reports undelivered notifications rather than iterating forever. The card’s observer only reads and updates a separate status line; it does not resize the observed card in response.
Geometry is now available, possibly as fractional CSS pixel coordinates even though offsetWidth itself is an integer. Those coordinates establish where drawing happens. They still do not establish which overlapping thing should be visible on top, or turn a glyph outline into colored device pixels. Paint answers the next part.
Drawing instructions in the right order
The browser now knows the notebook’s title occupies particular line fragments, the button has a border box, and the badge is positioned at a corner. Painting turns those results into drawing instructions: fill this background, draw this border, draw these glyphs, apply this clip. Engines can record these instructions in display lists or paint records, retaining them so that later work can reuse unchanged pieces.
Paint recording and rasterization are different operations. Recording a command to draw text does not necessarily touch every destination pixel immediately. Rasterization executes drawing work into a pixel resource later. DevTools labels and engine internals vary, so keep the distinction in mind when a trace contains both Paint and Raster tasks.
The order of drawing is observable. Our badge overlaps the notebook card. If a neighbor overlaps the badge too, which is on top? DOM order is part of the answer, but positioning and stacking contexts alter it. A An atomic group in the stacking order. Its descendants are ordered internally, then the group participates as one unit in its parent stacking context. gives descendants a local ordering system that cannot be escaped with a larger child z-index.
The root establishes a stacking context. Others arise from, among other things, opacity below 1, a transform other than none, isolation: isolate, and positioned elements with a non-auto z-index. Fixed and sticky positioning create contexts too; flex and grid items with non-auto z-index are another case. Filters, masks, containment and the top layer add further rules. A stacking context is a painting relationship, not a promise of a dedicated GPU texture.
Which declaration makes a boundary?
| Trigger | Exact condition |
|---|---|
| Root element | The document root establishes the root stacking context. |
| Position + z-index | relative or absolute positioning with z-index other than auto. fixed and sticky establish contexts even with z-index: auto. |
| Flex or grid item | A non-auto z-index creates a context, including when position is static. |
| opacity | A computed opacity below 1 groups the element and its descendants for compositing. |
| Transforms | transform other than none on a transformable element. Individual translate, rotate and scale values other than none also create contexts, even for identity transforms. |
| perspective | A value other than none creates a context on an element to which perspective applies. |
| filter / backdrop-filter | A computed value other than none creates a context; the filter rule excludes the document root, which already has its root context. |
| Blending and isolation | mix-blend-mode other than normal, or isolation: isolate. |
| Clipping and masking | clip-path, mask-image or mask-border-source other than none, on an element to which the property applies. overflow: hidden alone does not create a stacking context. |
| Layout / paint containment | Applied layout containment or paint containment, including contain: content and contain: strict. Size or style containment alone does not establish a context. |
| will-change | Naming a property whose non-initial value would create a stacking context creates one in advance. transform and opacity qualify; left does not. |
| Animation effects | While animations apply, stacking-context-creating properties are treated as if included in will-change. A finished animation with forwards or both fill retains that treatment. |
| Top layer | An element rendered in the top layer, such as an open modal dialog, and its ::backdrop each form a context placed outside ordinary document stacking. |
A formatting context and a stacking context are separate boundaries. In the currentcontainer-type rules, size and inline-size query containers impose size/style containment; container-type alone does not imply the layout/paint containment trigger. Other declarations on the same element can still create a context.
z-index is local
In the figure, the card starts as a positioned element with z-index: auto, so it does not establish a stacking context through positioning alone. Its positioned badge can compete with the neighboring element in the scene’s context. At a badge z-index above 2, the badge paints above the neighbor. At 2, the neighbor wins because it occurs later in tree order.
Set opacity on the card to 0.95. That groups the card and its descendants so they can be blended as a unit. The group participates at stack level 0 in this example, below the neighbor at 2. Even a badge at 12 remains inside that earlier group. The number is perfectly effective within the group; it just is not compared directly with 2 in the parent context.
A transform of translateX(0) can produce the same ordering change despite moving the card no visible distance. The computed transform is no longer none, which creates a stacking context. It also establishes a containing block for positioned descendants under the transform rules, including fixed descendants. A seemingly harmless “performance hack” can therefore change both stacking and positioning behavior.
CSS 2 Appendix E spells out the detailed painting order. A useful route through its rules is: the context’s background and border, negative-level positioned contexts, in-flow content and floats according to their categories, positioned content at zero/auto levels, then positive-level contexts. Inline painting and decorations have their own substeps. The figure isolates positioned boxes so you can inspect the context boundary without needing all of those rules at once.
Changed pixels are not always the whole page
A background-color change can leave the layout tree’s geometry intact but invalidate painted content. Engines track paint invalidations and damage so they can repaint affected regions and reuse the rest. Clips, filters, shadows and blending may enlarge the affected area. The bounding box of the DOM node you edited is not a universal bound on the work.
Consider our cart update. The badge’s character changes from 0 to 1, requiring new glyph content. The button’s label changes too, which may change its size and the positions of surrounding boxes before paint even begins. Later, if only the badge’s transform animates and its visual contents stay fixed, the browser has an opportunity to move already-painted content instead of recording and rasterizing those glyphs again.
This suggests a useful debugging order. First inspect which geometry changed. Then inspect paint flashing or paint records to see which regions were invalidated. Finally inspect compositing behavior. Adding will-change before understanding why every animation tick rewrites text cannot eliminate that text’s need for new pixels.
A stacking context keeps its descendants together in the paint order. A child’s large z-index cannot escape that boundary.
Move the pixels you already have
The card’s drawing commands still need pixels. In Chromium, painted content can be divided into tiles and rasterized into resources that the compositor can use. Tiling lets the engine prioritize visible regions and avoid treating an entire long document as one enormous bitmap. Raster work can run on worker threads, with GPU raster paths executing drawing through the GPU; software paths also exist.
The renderer compositor combines the resulting resources with property information: transforms, clips, effects and scrolling. A main-thread update commits new state across the thread boundary. The compositor can keep using the last committed state while the main thread is busy. That separation makes smooth scrolling and some animations possible during JavaScript work.
A compositor layer is an implementation choice, rather than an HTML element type. Several elements can contribute to one composited resource, and a single visual effect can need additional intermediate surfaces. A DOM tree, a stacking-context tree and a layer representation describe related but different structures. Counting div elements does not tell you how many textures the GPU holds.
Transform changes placement; width changes geometry
When an eligible transform or opacity animation runs on the compositor, it can sample the animation and update how existing pixels are placed or blended. It does not need JavaScript to calculate every intermediate position. The CSS transform rendering model leaves surrounding normal-flow geometry in its original place, although transforms affect overflow and other rendering behavior.
Animating width changes the geometry from which content is laid out. Animating left changes a positioned box’s geometric location and usually needs main-thread style/layout work. Neither is generally the same compositor-only property update as a promoted transform animation. A width change can also rewrap text; moving a prepainted rectangle cannot reproduce new line breaks.
Start the animations, then opt into blocking the main thread. Nothing animates on load.
Actual CSS-property animations via Web Animations. Compositor promotion depends on this browser and device; reduced-motion preference keeps the badges still.
The figure animates CSS properties through Web Animations. It does not drive either badge with a JavaScript requestAnimationFrame loop. That distinction is essential: a JavaScript loop that updates transform still needs the main thread to calculate and submit each update. A compositor-capable property does not automatically move your JavaScript to another thread.
Start the animations, then run the long task while they are moving. On a browser that promotes the transform animation, that badge can continue through the stall while the left animation pauses and catches up. Promotion, raster readiness, the rendering backend and device conditions affect what you observe. If both pause, inspect an engine trace before concluding that transform and left have identical dependencies. Reduced-motion mode keeps both badges still.
Memory is the other half of the bargain
Retaining pixels buys reuse at a memory cost. A plain RGBA8 image at 800 by 600 device pixels takes 800 × 600 × 4 = 1,920,000 bytes before overhead. At device-pixel ratio 2, a surface covering 800 by 600 CSS pixels has four times as many pixels. Tiling, multiple buffers, alignment, intermediate effects and driver allocations can raise the total beyond that simple calculation.
will-change is a hint that gives an engine time to prepare for a likely change. It can lead to earlier resource allocation or promotion, and can also create stacking or containing-block behavior when the hinted property would do so. It is not a force-GPU flag. Applying it to every product card can consume memory, increase raster and upload work, and make the page slower.
Prepare only the element that is about to animate when you have evidence that preparation helps, and release the hint when it is no longer useful. The cost of a fresh layer also matters for a very short animation: preparation can dominate a movement that lasts only a few frames. Scaling content can expose another tradeoff, because cached raster at the old resolution may become blurry or require rerasterization at the new scale.
The card’s initial text update still travels through main-thread rendering. Once its badge content is stable, the eight-pixel lift can reuse the committed pixels. We have now found why two visually similar movements can have different thread dependencies. The remaining question is when a browser gets to perform those updates while JavaScript keeps scheduling more work.
Where a frame fits in the event loop
The click handler is a piece of script run during an event-loop task. A timer callback is another task. So is much work triggered by loading and input. There is not one universal FIFO containing every kind of event: HTML defines task sources and queues, and the user agent chooses runnable work subject to ordering constraints.
A microtask queue is separate. Promise reactions and queueMicrotask callbacks enter it. At a microtask checkpoint, the browser drains the queue until it is empty, including microtasks added by other microtasks. Returning from one callback therefore does not necessarily make rendering possible: a self-replenishing microtask chain can keep the checkpoint busy.
The HTML event-loop processing model runs a selected task and performs a microtask checkpoint. For window event loops, eligible documents can then have rendering work scheduled when a rendering opportunity exists. That opportunity depends on refresh timing, visibility and the user agent’s scheduling. There is no requirement that every task be followed by a paint.
requestAnimationFrame registers a callback for animation-frame processing during an update of rendering. It does not create an ordinary timer task and it does not mean “after paint.” Its useful position is before the frame’s later style/layout-related rendering work, so writes can contribute to that update. Each callback receives a timestamp associated with the frame; use elapsed time rather than assuming that every callback represents exactly 16.67 ms.
button.addEventListener("click", () => {
card.toggleAttribute("data-added");
queueMicrotask(() => updateCartSummary());
requestAnimationFrame(() => {
// Writes can join this rendering update.
badge.style.transform = "translateX(20px)";
});
});There is a subtler checkpoint inside animation callback processing. After a callback returns and script cleanup leaves the JavaScript execution-context stack empty, queued microtasks run before the next rAF callback. A microtask queued inside the first rAF callback can therefore run before a second callback for the same update. Treating all rAF callbacks as one indivisible JavaScript batch gives the wrong result.
The lab accepts a small scheduling language instead of arbitrary executable source. Each line runs synchronously or registers a callback from one starting task. Promise and microtask commands share a FIFO queue. raf-micro registers a rAF callback that adds a microtask. Two model choices expose different allowed placements of rendering. The real run checks timer/rendering interleavings, rather than pretending a zero-delay timer always wins or always loses.
Grammar: sync, promise, microtask, timeout, raf or raf-micro, then one unique label. raf-micro queues a microtask named label.micro inside that rAF callback. Each line schedules from the same starting task. No JavaScript is evaluated.
Real trace appears here.
Ready. The browser may choose a rendering opportunity before, between or after timer tasks.
Inside an update of rendering
Ordered summary of the current HTML update-the-rendering algorithm. Numbers refer to its steps; each pass over documents follows the established document order. A rendering opportunity queues work on the rendering task source.
- HTML 1–5Select documents
Capture the frame timestamp. Order fully active documents with containing documents before their children and sibling containers in tree order. Filter render-blocked, hidden, view-transition-suppressed or currently ineligible documents; skip unnecessary or otherwise deferred updates.
- HTML 6–7Reveal and autofocus
Reveal each remaining document, then flush autofocus candidates for top-level traversables.
- HTML 8–10Resize, scroll, media
Run resize steps, then scroll steps, then evaluate media queries and report changes, in that order.
- HTML 11–13Other pre-frame updates
Update animations and send their events using the frame timestamp, run fullscreen steps, then handle detected 2D canvas context loss and restoration.
- HTML 14Animation-frame callbacks
Run rAF callbacks with the frame timestamp. Script cleanup can perform a microtask checkpoint after each callback, before the next callback is invoked.
- HTML 15–16Style, layout and resize observations
Record the style/layout start time. For each document, recalculate style and layout and determine content-visibility:auto proximity. Newly relevant content on its initial determination repeats this calculation immediately. Gather and broadcast active ResizeObserver observations, repeating with the updated depth until none remain; report skipped observations as a resize-loop error.
- HTML 17–18Focus and view transitions
Fix up focus if its current target is no longer focusable, then perform pending view-transition operations.
- HTML 19Intersection observations
Update intersection observations using the rendering timestamp. This computes observations; notification uses its separately queued task.
- HTML 20–21Timing bookkeeping
Record rendering time, then mark paint timing.
- HTML 22–23Render and finish
Update the document’s rendering or user interface, then process top-layer removals. Raster and presentation work can continue through engine-specific threads and queues.
This ordering is why changing a class and immediately awaiting Promise.resolve is not a reliable “wait until the page has painted” technique. The continuation is a microtask, which can run before any rendering opportunity. Even awaiting one rAF places your continuation in pre-paint callback processing. Two animation frames often span an opportunity in a visible document, but are not a portable proof that a physical display has shown the earlier image.
requestIdleCallback serves a different goal: do optional work when the browser estimates spare time. Its deadline exposes timeRemaining, and a timeout can force eventual callback scheduling even when the browser is busy. A timed-out idle callback does not magically receive a free frame budget. Keep its work bounded, and do not make immediate cart feedback depend on an idle period arriving.
A long task is conventionally one lasting more than 50 ms in the Long Tasks API. That diagnostic threshold is much longer than a 120 Hz refresh interval. You can miss frames without producing a long-task entry. Conversely, a long task includes associated execution work; a short-looking handler can still trigger expensive synchronous layout or a long microtask checkpoint.
Interaction to Next Paint, or INP, measures the responsiveness of qualifying click, tap and keyboard interactions across a page visit, accounting for input delay, processing and delay to the next presentation. It is not simply the duration of the event handler or an average frame rate. A cart handler that finishes quickly but leaves expensive rendering work before feedback can still produce poor interaction latency. The INP definition and aggregation rules define a high-percentile rule: discard one highest-latency interaction for every 50 interactions, then use the slowest remaining one. For fewer than 50 interactions, the maximum is reported; at 50–99 interactions, the second slowest is reported. At 100–149 it is the third slowest. This approximates the 98th percentile on busy pages. The 75th-percentile value used for Core Web Vitals assessment aggregates separate page visits, rather than changing this within-visit interaction rule.
Yield a task boundary when work can wait
For a batch of independent card updates, break work into small chunks. Where supported, scheduler.yield lets an async function suspend and resume in a later task with continuation scheduling rules. It gives the browser an opportunity to run other work; a resolved promise alone does not create that task boundary. Feature-detect the API and retain a timer-based fallback when needed. The API remains defined in the Prioritized Task Scheduling draft.
async function updateCards(cards) {
for (let start = 0; start < cards.length; start += 20) {
for (const card of cards.slice(start, start + 20)) update(card);
if (globalThis.scheduler?.yield) await scheduler.yield();
else await new Promise((resolve) => setTimeout(resolve, 0));
}
}The size of a useful chunk depends on measured work, not a universal number of cards. Give the clicked card its immediate state change first, then schedule less urgent summaries or background processing. A worker can move pure computation off the window thread, but it cannot directly mutate this DOM; sending a huge result back can still create a large rendering task. The frame deadline remains at the point where work becomes visible.
Microtasks drain before the event loop moves on. Rendering gets opportunities, not a guaranteed turn after every callback.
The last millisecond before light
The card has been parsed, styled, laid out, painted and rasterized. The compositor has a new frame. Yet a frame existing in memory is not the same as a reader seeing it. Resources must become ready, a display composition must be selected, and the display system must present that image at an appropriate time.
In Chromium, the renderer submits compositor frames containing resources and draw information. Viz aggregates submitted surfaces and prepares display composition. The operating system and graphics stack then participate in presentation. Some arrangements can use hardware overlays or direct scanout for eligible surfaces; others compose into another target. The precise copies, queues and process boundaries depend on the operating system, driver and rendering path.
BeginFrame is Chromium’s scheduling signal for producing an update against frame timing. It is not a JavaScript event fired whenever your page wants pixels. The scheduler coordinates main-thread and compositor work against deadlines, deciding which available state can be used. A late main-thread result can miss the intended frame while the compositor continues to use the previous committed state.
Vsync refers to synchronization around the display’s refresh timing. Presentation systems aim to switch the selected image at an appropriate boundary, avoiding a visible split between images that would result if a buffer changed mid-scan. A missed boundary can add another interval of latency. Hardware, operating-system composition and browser scheduling together determine when a completed image becomes eligible to appear.
Frame + resourcesViz / GPU process
Display compositionOS / presentation
Selected bufferDisplay controller
Scanout
At 0% of a conceptual top-to-bottom scan. A refresh is a time interval, not an instantaneous whole-screen flash.
Schematic scanout on a fixed-refresh display. Panel driving, blanking intervals, compositing and direct-scanout paths vary by device.
Buffers separate producing from displaying
Double buffering provides a simple conceptual separation: one image is being displayed while another is being prepared. The producer must not overwrite an image that the display system is still consuming. A third buffer can give the producer somewhere else to work while earlier images are queued or in use. The extra capacity can improve throughput or absorb timing variation, but a queue of older completed images can also increase input-to-display latency.
Those names do not establish a universal browser buffer count. A page may have tiled backing resources, intermediate render targets, compositor output buffers and operating-system presentation buffers. A phrase such as “triple-buffered” describes one part of that chain. To reason about latency, ask which stage owns each image and whether it is waiting behind older work.
Synchronization primitives keep consumers from reading incomplete output. A CPU can submit GPU commands and continue before those commands finish. The next consumer needs a signal that the resource is safe to use. That wait may be short, or it may reveal that rasterization or GPU execution is the bottleneck even when the renderer’s main thread looks idle.
The display controller reads the selected pixel data and sends it toward the panel according to its timing. On a conventional raster-scanned display, different rows are delivered at different moments within the refresh interval. Panel electronics and pixel response add their own delays. A frame does not become light everywhere at one mathematical instant, and requestAnimationFrame timestamps are not measurements of the moment a particular pixel emitted light.
Variable-refresh-rate displays can vary when a new scan begins within supported limits, helping presentation track completed frames instead of always waiting for one rigid cadence. VRR does not let a browser interrupt a running JavaScript task or remove the time needed for layout and rasterization. Browser, OS and display support determine whether a given presentation path actually benefits.
Follow the next expensive change backwards
Return to the notebook. Clicking the button creates a task. Text and state mutations invalidate styles and possibly geometry. A microtask checkpoint completes. At a rendering opportunity the main thread prepares the updated visual content, the compositor receives it, raster resources become ready, and a composed image reaches presentation. The badge’s later transform animation may reuse those pixels without revisiting the text and layout work.
When the response stutters, locate the dependency that missed its deadline. Did the input wait behind unrelated script? Did the handler repeatedly read geometry after writes? Did a new label rewrap many cards? Did a large shadow invalidate a broad paint area? Were there too many retained surfaces to raster and keep resident? Did completed GPU work arrive too late for presentation? Each question points to a different remedy.
Use the browser’s performance trace to connect a real interaction with scripting, style, layout, paint, raster and frame timing. Use layer and paint tools to explain reuse and invalidation. Compare a representative device and refresh rate. A task that fits comfortably on your development machine may cross the deadline on a phone, and a change that helps main-thread time can still increase GPU memory or presentation latency.
HTML describes objects and relationships. CSS describes constraints and drawing. JavaScript changes that description over time. The browser’s achievement is turning the latest useful description into a stable stream of images while input and computation keep arriving. A fast card interaction comes from making the necessary work small enough, and letting the browser reuse everything that remains true.
The image still has to reach a display deadline after the page’s code finishes. Optimize the stage that actually delays the visible response.
End of Browser rendering · 9 levels, Idea to Silicon
Where to next
Next in Web and networking · 12 of 12
WebAssembly, top to bottom
Start with real C zlib compressing your text in this tab. Then go down through the JavaScript boundary, the module format and the stack machine to the guard pages and x86-64 an engine uses to run it fast and safely.
Practical notes
Find what makes a page interaction slow
Use Event Timing to separate input delay, handler work and presentation delay, then correlate slow interactions with long animation frames and a DevTools trace.
Put card buttons beside links, not inside them
Give navigation and actions separate HTML controls. A sibling link and button work with the mouse, keyboard and assistive technology without event-cancellation patches.