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.
- 01Explain 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.
- 02Predict how far a change reachesTell which elements a class, a :has() rule or a custom property makes Chrome restyle, and keep that number small.
- 03Measure 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:
Here are the main numbers as code:
// 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 printsThe 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.
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
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:
.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".
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 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 msand.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:
htmlbodymainul#reviewsli#review-14.reviewp.review-textthe element Chrome is styling
- 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. - Nothing left to check. The selector is just
.review-text. Being in the right drawer already proves it: a match.
Chrome took 2 steps for this rule on Ben's review words. Try each selector: the ones that stop early are the cheap ones.
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
.zalone, the list for the class z says: check the element itself.
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:
/* 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
#reviewsinside highlight. Those children are the 1,000 reviews, so the cards look the same.
// 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 msand.highlight #reviews > *: 5009 restyled in 11.9 ms.
*, 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 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 msanda class on body: 1000 restyled in 4.3 ms. Then it printsthe 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:
: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
#nightbox.: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:
.review.marked { background-color: #fff3c4; }The change: document.querySelector("#review-14").classList.add("marked");
10.031 msnot timed yetThe class marked goes on Ben's review only. The list for marked says: restyle this element.
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.
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:
// 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.0and3.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:
.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.
// 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 msandlines 1 and 3: 1001 restyled in 77.4 ms.
: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:
.helpful.voted { background-color: var(--accent); color: var(--card); }The change: document.querySelector("#review-14 .helpful").classList.add("voted");
10.037 msnot timed yetThe class voted goes on Ben's Helpful button, and only the button's own rule depends on it.
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 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
--readon the root element, as a percentage. It's the same as writing--read: 40%in the html element's style attribute.
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
--readand 4 px tall, along the bottom of the header. Until--readis set, it's 0% wide.
The course set --read once, in three ways, and timed each:
// 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 msandon 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.
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:
@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.
--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:
header { background: linear-gradient(#8fd3a8, #8fd3a8) left bottom / var(--read, 0%) 4px no-repeat, #2f5d46; }The change: document.documentElement.style.setProperty("--read", "40%");
5,00918.6 msnot timed yet--read on the root flows down to every element below it, because custom properties inherit.
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:
| Selector | Elapsed (ms) | Match attempts | Match count | % of slow-path non-matches |
|---|---|---|---|---|
.review:has(img) | 4.050 | 1,000 | 1 | 100 |
:root:has(#night:checked) | 1.088 | 1 | 1 | 0 |
.review | 0.369 | 2,000 | 2,000 | 0 |
main ul li p | 0.054 | 2,000 | 2,000 | 0 |
.helpful | 0.037 | 2,000 | 2,000 | 0 |
.stars | 0.029 | 1,000 | 1,000 | 0 |
.sale .review-name | 0.024 | 1,000 | 0 | 0 |
.review-name | 0.021 | 1,000 | 1,000 | 0 |
5.673 ms86.9 ms24.4 msRavi's rules as he wrote them. Chrome looks inside every review for an img, and only Ben's has one.
.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:
/* 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 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.
| What changed | Elements restyled | Recalculate style |
|---|---|---|
The class marked on Ben's review, with .review.marked | 1 element | 0.031 ms |
The class highlight on body, with .highlight .review | 1,000 elements | 4.3 ms |
The class highlight on body, with .highlight #reviews > * | 5,009 elements | 11.9 ms |
| The Night reading switch, with Ravi's rules as he wrote them | 5,007 elements | 24.4 ms |
| The Night reading switch, after the fix | 5,007 elements | 20.3 ms |
A vote, with .helpful.voted | 1 element | 0.037 ms |
A vote, with .review:has(.voted) too | 3 elements | 1.1 ms |
A vote, with #reviews:has(.voted) .helpful:not(.voted) too | 1,001 elements | 77.4 ms |
--read set on :root | 5,009 elements | 18.6 ms |
--read set on header | 4 elements | 0.4 ms |
--read set on header, registered | 1 element | 0.092 ms |
--read set on main | 5,004 elements | 17.9 ms |
--read set on main, registered | 1 element | 0.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?
- The class marked on Ben's review, with
.review.marked - The class voted on a Helpful button, with
.helpful.voted --readset on main, registered withinherits: 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 > * --readset on :root, not registered--readset on header, not registered
Sort each change by the elements Chrome has to restyle.
Common mix-ups
- "Long selectors are always slow." No.
main ul li pcost 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-namewas 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.
Chrome files every rule in a drawer before it styles anything. Under which name does it file .review > h3?
Under the tag h3. Chrome only tries the rule on h3 elements. For each one, it then checks that the parent has the class review.
Ravi tries this rule. When the class night goes on body, what does Chrome's list for night tell it to look for below?
.night .review-name { color: #e8efe9; }The class review-name. When night goes on body, Chrome checks only the elements below with that class: the 1,000 names, not all 5,009 elements.
Ravi adds a Compact switch that puts the class compact on body. Rewrite his rule so the switch restyles only the reviews.
.compact #reviews > * { padding: 6px 12px; }.compact .review { padding: 6px 12px; }It pads the same 1,000 cards. Now the list for compact names the class review, so Chrome restyles the reviews instead of everything in body.
In the Selector Stats playground, switch to the fixed page. Which selector is at the top now?
:root:has(#night:checked). With the photo rule gone, the night rule is the slowest one left, though Chrome tries it on only one element.
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?
About 80.2 ms. It's the same first tap as the opening, which took 23.4 ms with Selector Stats off. Collecting the stats slows Chrome down.
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?
main { box-shadow: 0 0 24px rgb(47 93 70 / var(--glow, 0)); }@property --glow {
syntax: "<number>";
inherits: false;
initial-value: 0;
}With inherits: false, a new value set on main stays on main. Chrome restyles 1 element instead of main and every review inside it.
Check your understanding
For each question, ask two things: how many elements does the change reach, and how much work is each one?
Question 1 of 7Chrome tries
main ul li pon Ben's review words. Which part does it check on the element first?Choose an answer to see the explanation.
Question 2 of 7Ravi's old rule
.sale .review-namewas tried on 1,000 names and matched none. Why did it cost almost nothing?Choose an answer to see the explanation.
Question 3 of 7What does the second line of the highlight example print?
Read the code, then predict// 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.
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.
Question 5 of 7Ravi sets
--readon :root on every scroll. Only the header draws the line. Why did Chrome restyle 5,009 elements?Choose an answer to see the explanation.
Question 6 of 7What does
inherits: falsein@property --readchange?Choose an answer to see the explanation.
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:
- Reduce the scope and complexity of style calculations, web.dev.
- CSS Style Calculation in Blink: rules filed by their last part, Chromium source.
- selector_filter.h: the quick check of the ancestors' names, Chromium source.
- selector_checker.cc: matching from right to left, and :has(), Chromium source.
- The truth about CSS selector performance, Microsoft Edge Blog.
- CSS Style Invalidation in Blink, Chromium source.
- invalidation_set.h: what each list holds, Chromium source.
- document.cc: Recalculate style and its element count, Chromium source.
- Selectors Level 4: the :has() pseudo-class, W3C.
- style_engine.cc: how a change inside reaches a :has() rule, Chromium source.
- CSS Color Module Level 4: opacity, W3C.
- CSS Custom Properties for Cascading Variables Level 1, W3C.
- CSS Properties and Values API Level 1: @property, W3C.
- computed_style.cc: when changed custom properties reach the children, Chromium source.
- Analyze CSS selector performance during Recalculate Style events, Chrome DevTools.
- element_rule_collector.cc: the SelectorStats trace event, Chromium source.
- TimelineSelectorStatsView.ts: the Selector Stats tab, Chrome DevTools source.
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.