completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Style recalculation

How Chrome matches CSS selectors and picks the elements to restyle, why :has() and custom properties reach so far, and how to measure it with Selector Stats.

By the end, you can
  • 01
    Explain how a selector is matchedChrome files each rule under its last part, rules most misses out with a quick check, then checks the rest from right to left.
  • 02
    Predict how far a change reachesTell which elements a class, a :has() rule or a custom property makes Chrome restyle, and keep that number small.
  • 03
    Measure it in DevToolsRead Elements affected on Recalculate style, and find the slow rule with Selector Stats.

One switch, five thousand elements

It's late, and Asha is reading reviews of Leaf and Kettle's mint tea on her phone. Ravi builds the shop's site. He has added a Night reading switch at the top of the page. Asha taps it, and the whole page turns dark.

Ravi's page now shows all 1,000 reviews. Each review has five elements: the card, a name, the stars, the words and a Helpful button. With the header and the rest, the page has 5,016 elements.

Here is what Asha saw, in real frames from Chrome, and what Chrome did in between:

Two real frames of Asha's screen on Ravi's reviews page, cut to their top part. Just before her tap, the page is light. 63.6 ms after her tap, the same page is dark. Below, the main thread after the tap, to scale: Recalculate style from 26.5 ms to 49.9 ms, 5,007 elements, then pre-paint, paint and commit until 56.3 ms.Just before her tap63.6 ms after her tapRavi's reviews page in its light colours, with the Night reading switch off.The same page in its dark colours, with the Night reading switch on.Recalculate style: 23.4 ms, 5,007 elementstap, 0 msdark frame, 63.6 mspre-paint, paint, commit
Real frames from the course's recording in Chrome, cut to the top of Asha's screen. Below them, what the main thread did after her tap, to scale. Recalculate style was the longest step.

Here are the main numbers as code:

Asha's tap on Night readingPop out in the code editor (opens in a new tab)JavaScript
// Asha's tap on Night reading, from Chrome's trace.// Times are in milliseconds (ms) after her tap.const tap = { styleMs: 23.4, elements: 5007, onPage: 5016, darkFrame: 63.6 }; console.log(`Recalculate style: ${tap.styleMs} ms, ${tap.elements} of ${tap.onPage} elements`);console.log(`The dark page was on screen at ${tap.darkFrame} ms.`);console.log(`Style took ${Math.round((tap.styleMs / tap.darkFrame) * 100)}% of that wait.`);
  • Lines 1 and 2 are comments. A millisecond (ms) is a thousandth of a second.
  • Line 3 holds what Chrome's trace recorded. A trace is Chrome's detailed record of everything it did, as in lesson 7.2.
  • Line 5 prints Recalculate style: 23.4 ms, 5007 of 5016 elements. Line 6 prints The dark page was on screen at 63.6 ms.
  • Line 7 prints Style took 37% of that wait.

Recalculate style is DevTools' name for style recalculation. You met it in lesson 6.3. The browser works out which CSS rules apply to each element. Then it works out the final value of every property. The result for one element is its computed style.

Here, Chrome redid that for almost every element on the page. Why it matters: on Asha's phone, more than a third of her wait was this one step.

Ravi has two questions. Why did one tap restyle 5,007 elements? And what made each of them cost time? This lesson answers both, with real recordings.

Real-life analogyNew price labels for the whole shop

Meera raises the price of mint tea. First she works out which jars need a new label: only the mint jars. Then she writes each label. If every price in the shop goes up, every jar needs a label. The job takes the number of jars, times the time for one label.

In real life: Working out which jars need a new label
In JavaScript: Finding the elements a change might affect
In real life: Writing one label
In JavaScript: Matching the rules and building one element's style
In real life: Every price in the shop goes up
In JavaScript: The Night reading switch: every element's colours change
In real life: The jars, times the time per label
In JavaScript: Elements affected, times the work for each
The main idea

A style recalculation costs two things multiplied: how many elements a change reaches, and how much work each one takes. Your selectors, and the values that pass down the page, decide the reach. The rules Chrome has to match and apply decide the work.

How the course recorded it

  • The browser: Chrome 157, on a screen the size of Asha's phone: 412 by 823 px. Its processor, the CPU, was slowed 4 times, as in lesson 28.2.
  • The page: Ravi's reviews page, with 1,000 reviews. Each version of the page differs only in a few CSS rules.
  • The changes: the course made each change 9 times, with JavaScript run in the page. It kept the middle Recalculate style. The opening tap was a real mouse click.
  • The times: they come from the course's own computer, so yours will differ. The element counts won't.

How Chrome matches a selector

Start with the work for one element. A CSS rule is a selector and some styles. The selector picks the elements, like .review. To style one element, Chrome must find every rule whose selector matches it. Here are three of Ravi's rules:

Three of Ravi's rulesCSS
.review:has(img) { border-color: var(--accent); }
main ul li p { margin: 4px 0 0; }
.sale .review-name { color: #b3261e; }
  • Line 1 gives a green frame to a review with an image inside. Ben's review has his photo. :has(img) means "that has an img somewhere inside".
  • Line 2 spaces out every paragraph in a list item, in a list, in main.
  • Line 3 is left over from last summer's sale. It made the names red while the page had the class sale. Nothing has that class now.

Checking every rule against every element would be slow. web.dev puts the worst case as "the number of elements multiplied by the selector count". Chrome does three things to stay far from that.

1. Rules are filed by their last part

Before it styles anything, Chrome files every rule under the last part of its selector. Blink's notes on style call it the "right-most compound selector". .review:has(img) is filed under the class review. .sale .review-name is filed under the class review-name.

For each element, Chrome opens only the drawers that fit it: its id, its classes and its tag. There's also a drawer for rules whose last part could fit any element. A rule in any other drawer is never even tried. It's like a post office that sorts letters by street, so each postman reads only his own street's letters.

2. From right to left

When Chrome tries a rule, it checks the last part first, on the element itself. Then it walks up, parent by parent, to check the rest. The Microsoft Edge team describes it the same way: the engine reads a selector "from right to left".

Real-life analogyWho has the green umbrella?

At the Leaf and Kettle, Meera calls out: "The guest with the green umbrella, in the garden room, your tea is ready." Every guest looks at their own umbrella first. Most don't have a green one, and they're done. Only the few who do check which room they're in.

In real life: Looking at your own umbrella
In JavaScript: Checking the selector's last part on the element
In real life: Checking which room you're in
In JavaScript: Walking up to the parents for the rest
In real life: Most guests are done at once
In JavaScript: Most rules fail on their last part

3. A quick check of the names above

As Chrome walks down the page, it keeps a list of names from every element above: tags, ids, classes and attributes. Blink's code calls this list a Bloom filter. Before Chrome tries a rule that needs something above, it looks the name up. If the name isn't there, the rule can't match, and Chrome moves on at once.

The list can say "maybe" by mistake, but never "no" by mistake. So a rule that passes is still checked in full. Blink's comment says the filter can "discard 60-70% of rules in early processing".

Selector Stats, from lesson 7.5, shows both kinds of rule on Ravi's page:

Two of Ravi's rules in Selector StatsPop out in the code editor (opens in a new tab)JavaScript
// Two of Ravi's rules in Selector Stats, from the night tapconst rows = [  { selector: "main ul li p", tried: 2000, matched: 2000, ms: 0.054 },  { selector: ".sale .review-name", tried: 1000, matched: 0, ms: 0.024 },];for (const row of rows) {  console.log(`${row.selector}: tried ${row.tried}, matched ${row.matched}, ${row.ms} ms`);}
  • Lines 3 and 4 are two rows from the night tap. Each says how many elements Chrome tried the rule on, how many it matched, and the time.
  • Line 7 prints main ul li p: tried 2000, matched 2000, 0.054 ms and .sale .review-name: tried 1000, matched 0, 0.024 ms.

The long selector matched 2,000 paragraphs. Walking up three levels for each cost 0.054 ms in all. The sale rule never got past the quick check, because nothing above the names has the class sale. Why it matters: a long selector isn't slow by itself. Measure before you rewrite one.

Pick a selector below to see the steps Chrome takes on Ben's review words:

Playground: one rule, one element
Ben's review wordsand every element above
  1. html
  2. body
  3. main
  4. ul#reviews
  5. li#review-14.review
  6. p.review-text the element Chrome is styling
Chrome's stepsmatch
  1. Filed under. The last part is .review-text, so Chrome files this rule under the class review-text. This element is in that drawer, so Chrome tries the rule.
  2. Nothing left to check. The selector is just .review-text. Being in the right drawer already proves it: a match.
Try it yourself
.review-text matches

Chrome took 2 steps for this rule on Ben's review words. Try each selector: the ones that stop early are the cheap ones.

A model of the steps, written for this lesson from Blink's source (style-calculation.md, selector_filter.h and selector_checker.cc). It isn't Chrome itself: Chrome's quick check can say “maybe” by mistake, and Chrome does more for some selectors.

How Chrome decides what to redo

Matching is the work for one element. But which elements? After a change, Chrome must find every element whose style might now be wrong. Marking those elements is called invalidation. The simplest way would be to mark them all, every time. Blink's notes on invalidation call that "the simplest possible approach". Chrome does better.

So Chrome prepares ahead. When it reads a stylesheet, it builds a small list for each name in each selector. Blink calls these lists invalidation sets. A list says: "when this name changes on an element, check these elements below it". Blink's code gives examples:

  • For .y .z, the list for the class y says: check the elements below with the class z.
  • For .v *, the list for the class v says: check everything below. Blink calls that the whole subtree.
  • For .z alone, the list for the class z says: check the element itself.
Real-life analogyMeera's notebook of who to tell

Meera keeps a notebook by the door. Under "evening sign", it says: tell the waiters with a red badge to light the candles. When she hangs the sign, she tells only them. Another page says "tell everyone in the room". For that one, she speaks to every person, even guests who don't care.

In real life: Hanging the evening sign
In JavaScript: Adding a class to body
In real life: The notebook's page for that sign
In JavaScript: The invalidation set for that class
In real life: Waiters with a red badge
In JavaScript: The elements with the class review
In real life: "Tell everyone in the room"
In JavaScript: A rule that ends in *: the whole subtree

Ravi wants a Highlight switch that turns every review card pale yellow. His code adds the class highlight to body. The course built two pages that differ in one rule:

The same yellow cards, two waysCSS
/* One page has this rule */.highlight .review { background-color: #fff3c4; }/* The other page has this one */.highlight #reviews > * { background-color: #fff3c4; }
  • Line 2 colours every element with the class review inside an element with the class highlight.
  • Line 4 colours every child of the list #reviews inside highlight. Those children are the 1,000 reviews, so the cards look the same.
Two ways, timedPop out in the code editor (opens in a new tab)JavaScript
// The class highlight goes on body. Middle of 9 tries each.const pages = [  { rule: ".highlight .review", elements: 1000, ms: 4.3 },  { rule: ".highlight #reviews > *", elements: 5009, ms: 11.9 },];for (const page of pages) {  console.log(`${page.rule}: ${page.elements} restyled in ${page.ms} ms`);}
  • Lines 3 and 4 hold each page's Recalculate style after the class went on body.
  • Line 7 prints .highlight .review: 1000 restyled in 4.3 ms and .highlight #reviews > *: 5009 restyled in 11.9 ms.
Two copies of Ravi's page after the class highlight went on body. With .highlight .review, Chrome restyled only the 1,000 reviews: 1,000 elements. With .highlight #reviews > *, it restyled body and everything inside it: 5,009 elements..highlight .review.highlight #reviews > *bodyheader, 3 insidemainh1ul#reviews1,000 li.review4,001 inside thembodyheader, 3 insidemainh1ul#reviews1,000 li.review4,001 inside them1,000 restyled5,009 restyled
Shaded: the elements Chrome restyled when the class highlight went on body. Both rules colour the same 1,000 cards. The second one ends in *, so Chrome marks everything below.

The cards are the same. But the second page restyled every element in body, five times as many. It took almost three times as long. Its rule ends in *, which names nothing, so the list for highlight could only say "everything below".

With Selector Stats on, Chrome's trace also says why it marked each element. On the first page, it logged "Invalidation set matched class" 1,000 times, once per review. On the second, it logged "Invalidation set invalidates subtree" once, for body. Why it matters: end a selector with a class that names what changes, so Chrome's list can name it too.

Blink's notes add that these lists "err on the side of correctness". They may mark an element that ends up the same. A wasted check is better than a wrong colour.

Counting the elements a change reaches

DevTools counts the elements for you. Click a Recalculate style event in the Performance panel, and its summary shows Elements affected, as in lesson 28.2. Chrome counts each element whose style it worked out in full during that event. Here are three changes on Ravi's page:

Three changes, three countsPop out in the code editor (opens in a new tab)JavaScript
// Three changes on Ravi's page. Middle of 9 tries each.const changes = [  { change: "a class on Ben's review", elements: 1, ms: 0.031 },  { change: "a class on body", elements: 1000, ms: 4.3 },  { change: "the Night reading switch", elements: 5007, ms: 24.4 },];for (const c of changes) {  console.log(`${c.change}: ${c.elements} restyled in ${c.ms} ms`);}
  • Line 3 is the class marked on Ben's review, with the rule .review.marked.
  • Line 4 is the highlight page with .highlight .review.
  • Line 5 is the Night reading switch.
  • Line 8 prints a class on Ben's review: 1 restyled in 0.031 ms and a class on body: 1000 restyled in 4.3 ms. Then it prints the Night reading switch: 5007 restyled in 24.4 ms. That's the middle of 9 taps. Asha's one tap in the opening took 23.4 ms.

The more elements a change reached, the longer it took. Why it matters: before you make each element cheaper, make the change reach fewer of them.

Why did the night switch reach 5,007 elements, when highlight reached 1,000? Ravi keeps his colours in custom properties:

Ravi's coloursCSS
:root { --paper: #fffdf8; --ink: #2b2b2b; --card: #ffffff; --line: #c9dccf; --accent: #2f5d46; }:root:has(#night:checked) { --paper: #16201b; --ink: #e8efe9; --card: #1f2b24; --line: #3d5446; --accent: #8fd3a8; }body { background-color: var(--paper); color: var(--ink); }.review { background-color: var(--card); border-color: var(--line); }.helpful { color: var(--accent); }
  • Line 1 sets five colours on the root element, html, as custom properties: names that start with two dashes.
  • Line 2 swaps in dark colours while the page has a checked #night box. :root:has(#night:checked) reads: "the root, if it has a checked #night inside".
  • Lines 3 to 5 use the colours with var().

Some CSS properties pass down from an element to the elements inside it, like color. That's called inheriting. Custom properties inherit too. So when the root's colours changed, every element below got new values. Blink's code shows the rule: when an element's inherited values change, its children are restyled next.

Why it matters: a change on the root, or on body, can reach every element, even without a *.

Try each change below. The playground shows what the course recorded in Chrome. It can also time the same change in your browser:

Playground: how far a class reaches
The rule on this pageCSS
.review.marked { background-color: #fff3c4; }

The change: document.querySelector("#review-14").classList.add("marked");

Class on Ben's reviewRecalculate style
Elements affected, in Chrome1
Time, in Chrome0.031 ms
Time, in your browsernot timed yet
Try it yourself
1 element restyled

The class marked goes on Ben's review only. The list for marked says: restyle this element.

Recorded in Chrome 157 with the CPU 4 times slower: the middle Recalculate style of 9 tries. "Time it" loads the same page below and makes the change 9 times in your browser, timing how long the browser takes to work out the new style. Your numbers depend on your computer.

When :has() looks inside, and changes reach up

:has() lets a rule look inside an element. The Selectors spec says it matches an element "if any of the relative selectors would match at least one element when anchored against this element". In plain words, .review:has(img) matches a review that has an img somewhere inside it. That's handy, and it costs work in two ways.

Looking inside costs time

To match .review:has(img), Chrome must look through each review's insides. Blink's code says checking every element below would be "far too slow to be usable in practice". So Chrome narrows the search by the selector's combinators: the symbols between its parts, like a space or >. :has(> img) only looks at children. Chrome also remembers answers during one recalculation.

Real-life analogyLunchboxes with an apple inside

A teacher puts a green sticker on every lunchbox with an apple inside. She has to open each box to look. "An apple on top" would be quicker: she'd only lift the lid. And when a child drops an apple in later, that box's sticker has to change.

In real life: Opening every lunchbox
In JavaScript: .review:has(img) looking through each review
In real life: Only lifting the lid
In JavaScript: :has(> img): children only
In real life: A child drops an apple in later
In JavaScript: A class added inside an element
In real life: Changing that box's sticker
In JavaScript: Chrome restyles the element with the :has() rule

The course timed the night tap with four versions of Ravi's photo rule:

Four photo rules, one night tapPop out in the code editor (opens in a new tab)JavaScript
// The night tap with four photo rules. Middle of 9 tries each.const rules = [  { rule: ".review.with-photo", ms: 20.3 },  { rule: ".review:has(> img)", ms: 21.2 },  { rule: ".review:has(img)", ms: 23.3 },  { rule: ":has(> img)", ms: 23.8 },];for (const r of rules) {  console.log(`${r.rule}: ${r.ms} ms, ${(r.ms - rules[0].ms).toFixed(1)} ms more`);}
  • Lines 3 to 6 hold the night tap's Recalculate style with each version.
  • Line 9 prints how much longer each one was than the first: 0.0, 0.9, 3.0 and 3.5 ms more.

A class costs almost nothing to check. Ravi's page can add it to a review that has a photo. .review:has(> img) looks only at each review's children: 0.9 ms more. .review:has(img) looks at everything inside: 3.0 ms more.

:has(> img) alone has no class, so it's filed with the rules for every element. Chrome tried it on all 5,007: 3.5 ms more. Why it matters: put a class in front of :has(), and use > when you can.

A change inside reaches up

Usually a change reaches down: a class on body reaches the elements below. With :has(), a change inside an element can change the element around it. So Chrome has to look up too.

Asha taps Helpful on Ben's review. Ravi's code adds the class voted to the button. The course built three pages:

Three ways to show a voteCSS
.helpful.voted { background-color: var(--accent); color: var(--card); }.review:has(.voted) { border-color: var(--accent); }#reviews:has(.voted) .helpful:not(.voted) { opacity: 0.5; }
  • Line 1 colours the button itself once it has the class voted. All three pages have it.
  • Line 2 gives Ben's whole review a green frame once a voted button is inside.
  • Line 3 fades every other Helpful button in the list, so Asha sees she has voted.
One vote, three pagesPop out in the code editor (opens in a new tab)JavaScript
// Asha taps Helpful on Ben's review. Middle of 9 tries each.const pages = [  { rules: "line 1", elements: 1, ms: 0.037 },  { rules: "lines 1 and 2", elements: 3, ms: 1.1 },  { rules: "lines 1 and 3", elements: 1001, ms: 77.4 },];for (const page of pages) {  console.log(`${page.rules}: ${page.elements} restyled in ${page.ms} ms`);}
  • Line 3 is the page with line 1 only. Line 4 adds line 2. Line 5 adds line 3.
  • Line 8 prints line 1: 1 restyled in 0.037 ms, lines 1 and 2: 3 restyled in 1.1 ms and lines 1 and 3: 1001 restyled in 77.4 ms.
Two copies of Ravi's page after the class voted went on Ben's Helpful button. With .review:has(.voted), Chrome restyled the button, Ben's review and the root: 3 elements. With #reviews:has(.voted) .helpful, it restyled the root and all 1,000 Helpful buttons: 1,001 elements..review:has(.voted)#reviews:has(.voted) .helpfulhtml, the rootbodymainul#reviewsli: Ben's reviewBen's Helpful button999 other Helpful buttonshtml, the rootbodymainul#reviewsli: Ben's reviewBen's Helpful button999 other Helpful buttons3 restyled1,001 restyled
Shaded: the elements Chrome restyled after the vote. The arrow climbs from the button to the element with the :has(). The root is shaded in both, because Ravi's night rule is a :has() rule too.

Line 1 is about the button itself, so Chrome restyled 1 element. With line 2, Chrome walked up from the button and restyled Ben's review. It also restyled a third element: the root.

Why the root? Ravi's night rule, :root:has(#night:checked), is a :has() rule too. Once the class voted appears in any :has() rule, Chrome walks up from the button. It marks every element above that has a :has() rule, without checking which class each one looks for. A note in Blink's code says it still needs "filtering for irrelevant elements". Selector Stats showed Chrome trying the night rule again, and it was the slowest row: 0.792 ms.

With line 3, the vote reached up to the list. From there, the rule named every Helpful button below it: 1,001 elements. Matching that rule took 1.881 ms, by Selector Stats. So most of the 77.4 ms went on something else.

One clue: the rule makes 999 buttons see-through. The CSS spec says a see-through box "forms a stacking context", a group drawn as one. Taking the vote back restyled the same 1,001 elements in 6.4 ms. Lesson 31.4 finds where the time went.

Why it matters: keep a :has() rule close to what changes. A :has() on the root, on body or on a long list can turn a small change into a big restyle.

Try the three pages here:

Playground: how far a vote reaches
The rule on this pageCSS
.helpful.voted { background-color: var(--accent); color: var(--card); }

The change: document.querySelector("#review-14 .helpful").classList.add("voted");

.helpful.votedRecalculate style
Elements affected, in Chrome1
Time, in Chrome0.037 ms
Time, in your browsernot timed yet
Try it yourself
1 element restyled

The class voted goes on Ben's Helpful button, and only the button's own rule depends on it.

Recorded in Chrome 157 with the CPU 4 times slower: the middle Recalculate style of 9 tries. "Time it" loads the same page below and makes the change 9 times in your browser, timing how long the browser takes to work out the new style. Your numbers depend on your computer.

Custom properties flow down the tree

Ravi adds a thin green line under the header that grows as Asha reads. His code works out how far down the page she is. Then it puts that in a custom property, --read:

Ravi's first versionJavaScript
// Ravi's first version: on every scroll, set --read on the rootaddEventListener("scroll", () => {  const read = scrollY / (document.documentElement.scrollHeight - innerHeight);  document.documentElement.style.setProperty("--read", `${Math.round(read * 100)}%`);});
  • Line 2 runs the function every time the page scrolls.
  • Line 3 works out how far down Asha is, from 0 at the top to 1 at the bottom.
  • Line 4 sets --read on the root element, as a percentage. It's the same as writing --read: 40% in the html element's style attribute.
The line under the headerCSS
header {  background: linear-gradient(#8fd3a8, #8fd3a8) left bottom / var(--read, 0%) 4px no-repeat, #2f5d46;}
  • Line 2 draws the line: a gradient as wide as --read and 4 px tall, along the bottom of the header. Until --read is set, it's 0% wide.

The course set --read once, in three ways, and timed each:

One new value, three waysPop out in the code editor (opens in a new tab)JavaScript
// Setting --read once, three ways. Middle of 9 tries each.const ways = [  { where: "on :root", elements: 5009, ms: 18.6 },  { where: "on header", elements: 4, ms: 0.4 },  { where: "on header, registered", elements: 1, ms: 0.092 },];for (const way of ways) {  console.log(`${way.where}: ${way.elements} restyled in ${way.ms} ms`);}
  • Lines 3 to 5 hold the three ways.
  • Line 8 prints on :root: 5009 restyled in 18.6 ms, on header: 4 restyled in 0.4 ms and on header, registered: 1 restyled in 0.092 ms.

On the root, one new value restyled 5,009 elements in 18.6 ms. A page can scroll many times a second. At 60 frames a second, one frame lasts 16.7 ms, as lesson 6.2 showed. So on Asha's phone, this one step took longer than a whole frame.

Real-life analogyA price board that every menu copies

At the Leaf and Kettle, each table has a little menu, copied from the big price board by the door. When Meera changes the board, someone has to update every table's menu. That includes tables that never order mint tea. A note on one table's menu changes only that table.

In real life: The big board by the door
In JavaScript: A custom property on :root
In real life: Every table's copy of the menu
In JavaScript: Every element inherits the value
In real life: Updating every menu
In JavaScript: Chrome restyling every element below
In real life: A note on one table's menu
In JavaScript: A property that doesn't inherit, set on one element

The spec for custom properties lists them as "Inherited: yes". So Chrome can't skip an element just because it never uses --read. Its inherited values changed, so it needs a new computed style.

Blink does have a shortcut. An element that uses no variables at all can get a quick copy of the new values, with no matching. DevTools doesn't count those. But Ravi's reviews use var() for their colours, so each one was worked out in full.

Setting --read on the header, the element that draws the line, cut the count to 4: the header and the three elements inside it. The third way registers the property first, with @property:

Registering --readCSS
@property --read {  syntax: "<percentage>";  inherits: false;  initial-value: 0%;}
  • Line 1 registers a custom property called --read.
  • Line 2 says its value is a percentage.
  • Line 3 says it doesn't inherit: the elements inside header don't get header's value.
  • Line 4 gives the value it starts with, 0%.

Each of the settings on lines 2 to 4 is called a descriptor.

The CSS Properties and Values spec says the inherits descriptor controls "whether or not the property inherits by default". With inherits: false, the value stays on the header alone: 1 element, 0.092 ms.

Three ways to set --read once. On the root, it flows down to every element below: Chrome restyled 5,009. On the header, it flows down to the header and the 3 elements inside it: 4. Registered with inherits: false, it stays on the header: 1.--read on :roothtmlbodyheader3 inside headermain1,000 reviewstheir insides5,009 restyled--read on headerhtmlbodyheader3 inside headermain1,000 reviewstheir insides4 restyledregistered, on headerhtmlbodyheader3 inside headermain1,000 reviewstheir insides1 restyled
Shaded: the elements Chrome restyled after one new value of --read. An unregistered custom property flows down to every element below. A registered one with inherits: false stays where it's set.

Registering matters most when the element that uses the value is big. The course also drew the line from main, which holds every review. Setting --read on main restyled 5,004 elements. Registered, it restyled 1.

Why it matters: set a custom property on the smallest element that uses it. If that element is big, register the property with inherits: false.

Compare all five ways here:

Playground: where --read goes
The rule on this pageCSS
header { background: linear-gradient(#8fd3a8, #8fd3a8) left bottom / var(--read, 0%) 4px no-repeat, #2f5d46; }

The change: document.documentElement.style.setProperty("--read", "40%");

On :rootRecalculate style
Elements affected, in Chrome5,009
Time, in Chrome18.6 ms
Time, in your browsernot timed yet
Try it yourself
5,009 elements restyled

--read on the root flows down to every element below it, because custom properties inherit.

Recorded in Chrome 157 with the CPU 4 times slower: the middle Recalculate style of 9 tries. "Time it" loads the same page below and makes the change 9 times in your browser, timing how long the browser takes to work out the new style. Your numbers depend on your computer.

Finding the slow rule with Selector Stats

Back to Asha's night tap. It restyled 5,007 elements, and it has to: every colour on the page changes. So Ravi can't shrink the count. He can only make each element cheaper. Which of his rules cost the most?

Lesson 7.5 showed how to turn on Selector Stats. In the Performance panel, open Capture settings and check Enable CSS selector stats. Here's where its numbers come from. Chrome writes a SelectorStats event into the trace right after each Recalculate style. For each selector, it adds up four things:

  • Elapsed: the time spent trying the rule, timed around each try.
  • Match attempts: how many elements Chrome tried it on, after filing.
  • Match count: how many of those it matched.
  • % of slow-path non-matches: of the misses, the share the quick check couldn't rule out.

It's like an itemised receipt. You see what each line cost, not just the total. Here are Ravi's rules from a night tap with Selector Stats on. Switch to the fixed page to compare:

Playground: Selector Stats for the night tap
Ravi's rulesSelector Stats
SelectorElapsed (ms)Match attemptsMatch count% of slow-path non-matches
.review:has(img)4.0501,0001100
:root:has(#night:checked)1.088110
.review0.3692,0002,0000
main ul li p0.0542,0002,0000
.helpful0.0372,0002,0000
.stars0.0291,0001,0000
.sale .review-name0.0241,00000
.review-name0.0211,0001,0000
All of Ravi's rules, Elapsed5.673 ms
Recalculate style, Stats on86.9 ms
Recalculate style, Stats off24.4 ms
Try it yourself
The top row: .review:has(img)

Ravi's rules as he wrote them. Chrome looks inside every review for an img, and only Ben's has one.

The rows Chrome wrote in its SelectorStats trace event after a night tap, read the way DevTools' Selector Stats tab reads them, sorted by Elapsed. Ravi's own rules only; the browser's built-in rules are left out. Chrome 157, CPU 4 times slower, the middle of 3 taps with Selector Stats on.

.review:has(img) tops the list at 4.050 ms. Chrome tried it on all 1,000 reviews and matched 1, Ben's. Every miss needed a full check, because the quick check can't see inside a review. Next comes :root:has(#night:checked). Chrome tried it on one element, the root. But to answer it, Chrome searches the page for a checked #night.

Ravi's fix: his page adds a class to a review that has a photo, when it builds the page. While he's there, he gives the paragraphs their own classes:

Ravi's fixCSS
/* Before */.review:has(img) { border-color: var(--accent); }main ul li p { margin: 4px 0 0; }/* After: Ravi's page adds class="with-photo" to a review with a photo */.review.with-photo { border-color: var(--accent); }.stars, .review-text { margin: 4px 0 0; }
  • Lines 2 and 3 are the old rules.
  • Line 5 gives the green frame to a review with the class with-photo. The page adds that class to Ben's review.
  • Line 6 spaces the paragraphs by their own classes.

Selector Stats slows Chrome down, so Ravi timed the fix with it off:

The fix, timedPop out in the code editor (opens in a new tab)JavaScript
// The night tap's Recalculate style, Selector Stats off. Middle of 9.const asIs = 24.4;const fixed = 20.3;const saved = asIs - fixed;console.log(`Saved ${saved.toFixed(1)} ms of ${asIs} ms: ${Math.round((saved / asIs) * 100)}%`);
  • Lines 2 and 3 are the middle Recalculate style of 9 night taps, before and after.
  • Line 5 prints Saved 4.1 ms of 24.4 ms: 17%.

That's about what Selector Stats said the photo rule cost. The paragraph classes made no real difference. With main ul li p put back, the night tap took 20.4 ms.

Now look at the totals. Ravi's rules took 5.673 ms of matching in all. The Recalculate style around them took 86.9 ms with Selector Stats on, and 24.4 ms with it off. web.dev quotes a Blink engineer on the two jobs in an element's style. Roughly half the time goes on matching selectors. The other half goes on building the style from the rules that matched. Selector Stats times only the matching.

Why it matters: Selector Stats points at the slow rule. Only a timing with it off shows what a fix saves.

Which change reaches how far?

Here is every change in this lesson, side by side. Read each row across: what changed, how many elements Chrome restyled, and the middle Recalculate style.

Every change, side by side
What changedElements restyledRecalculate style
The class marked on Ben's review, with .review.marked1 element0.031 ms
The class highlight on body, with .highlight .review1,000 elements4.3 ms
The class highlight on body, with .highlight #reviews > *5,009 elements11.9 ms
The Night reading switch, with Ravi's rules as he wrote them5,007 elements24.4 ms
The Night reading switch, after the fix5,007 elements20.3 ms
A vote, with .helpful.voted1 element0.037 ms
A vote, with .review:has(.voted) too3 elements1.1 ms
A vote, with #reviews:has(.voted) .helpful:not(.voted) too1,001 elements77.4 ms
--read set on :root5,009 elements18.6 ms
--read set on header4 elements0.4 ms
--read set on header, registered1 element0.092 ms
--read set on main5,004 elements17.9 ms
--read set on main, registered1 element0.088 ms

Now sort some changes by how far they reach. Ask: does the change stay on one element, reach the elements a rule names, or flow down to everything below?

How far does it reach?
  • The class marked on Ben's review, with .review.marked
  • The class voted on a Helpful button, with .helpful.voted
  • --read set on main, registered with inherits: false
  • The class highlight on body, with .highlight .review
  • The class sale on body, with .sale .review-name
  • A vote on Ben's review, with #reviews:has(.voted) .helpful:not(.voted)
  • The class highlight on body, with .highlight #reviews > *
  • --read set on :root, not registered
  • --read set on header, not registered
Try it yourself
0 of 9 correct

Sort each change by the elements Chrome has to restyle.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "Long selectors are always slow." No. main ul li p cost 0.054 ms for 2,000 paragraphs. .review:has(img), which looks shorter, cost the most.
  • "A class on body restyles every element." No. With .highlight .review, it restyled only the 1,000 reviews. Chrome's list named what to look for.
  • ":has() only looks inside its own element." No. A change inside reaches up to it, and then to every element the rule names: 1,001 for one vote.
  • "A custom property only affects the elements that use it." No. It inherits. Set on the root, it made Chrome restyle 5,009 elements.
  • "A rule that matches nothing costs nothing." No. Chrome still tries it. .sale .review-name was cheap because the quick check ruled it out, not because it matched nothing.
  • "Selector Stats shows a recalculation's whole cost." No. It times only the matching, and recording it slows Chrome down.

Practice exercises

Answer first, then use the hints.

Exercise 1 · Warm-upWhich drawer?

Chrome files every rule in a drawer before it styles anything. Under which name does it file .review > h3?

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upThe list for night

    Ravi tries this rule. When the class night goes on body, what does Chrome's list for night tell it to look for below?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    .night .review-name { color: #e8efe9; }

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeCompact cards

      Ravi adds a Compact switch that puts the class compact on body. Rewrite his rule so the switch restyles only the reviews.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      .compact #reviews > * { padding: 6px 12px; }

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeAfter the fix

        In the Selector Stats playground, switch to the fixed page. Which selector is at the top now?

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeThe tap, with Selector Stats on

          Download the course's trace of Asha's first tap, with Selector Stats on. Load it in DevTools' Performance panel. How long did the long Recalculate style take, in ms?

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA glow that stays on main

            Ravi's main glows more as Asha scrolls. His code sets --glow: 0.3 and other values on main. Which descriptor in an @property rule keeps each change on main alone?

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            main { box-shadow: 0 0 24px rgb(47 93 70 / var(--glow, 0)); }

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask two things: how many elements does the change reach, and how much work is each one?

              The style recalculation quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Chrome tries main ul li p on Ben's review words. Which part does it check on the element first?

                Choose an answer to see the explanation.

              2. Question 2 of 7Ravi's old rule .sale .review-name was tried on 1,000 names and matched none. Why did it cost almost nothing?

                Choose an answer to see the explanation.

              3. Question 3 of 7What does the second line of the highlight example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // The class highlight goes on body. Middle of 9 tries each.
                const pages = [
                  { rule: ".highlight .review", elements: 1000, ms: 4.3 },
                  { rule: ".highlight #reviews > *", elements: 5009, ms: 11.9 },
                ];
                for (const page of pages) {
                  console.log(`${page.rule}: ${page.elements} restyled in ${page.ms} ms`);
                }

                Choose an answer to see the explanation.

              4. Question 4 of 7Asha votes on Ben's review. With .review:has(.voted) on the page, Chrome restyled 3 elements. Which was the third, besides the button and the review?

                Choose an answer to see the explanation.

              5. Question 5 of 7Ravi sets --read on :root on every scroll. Only the header draws the line. Why did Chrome restyle 5,009 elements?

                Choose an answer to see the explanation.

              6. Question 6 of 7What does inherits: false in @property --read change?

                Choose an answer to see the explanation.

              7. Question 7 of 7Selector Stats added Ravi's rules up to a few milliseconds, but the Recalculate style around them took much longer. Why?

                Choose an answer to see the explanation.

              Key takeaways

              • A style recalculation costs the elements a change reaches, times the work for each one.
              • Chrome files each rule under its last part, rules out most misses with a quick check, then checks from right to left.
              • Invalidation sets name what to restyle. A selector ending in a class keeps the list short. One ending in * means everything below.
              • :has() looks inside, and a change inside reaches up to it. Keep it close to what changes.
              • Custom properties inherit. Set them on the smallest element that uses them, or register them with inherits: false.
              • Elements affected counts the reach. Selector Stats finds the slow rule. Time the fix with Selector Stats off.

              Remember the one-liner.
              Restyling costs reach times work: keep changes close to what they change, and selectors that name what they want.

              Sources

              The facts on this page come from these specs, docs and source files:

              Coming next: Layout and layout thrashing. After style comes layout. You'll see what makes it run again and again, and how to batch your reads and writes.

              CompleteFrontend Clear concepts. Working examples.