Constructable stylesheets
Learn constructable stylesheets: make a CSSStyleSheet in JavaScript, fill it with replaceSync(), and share it with every shadow root via adoptedStyleSheets.
- 01Make a sheet in JavaScriptCreate one with
new CSSStyleSheet(), fill it withreplaceSync()orreplace(), and know why@importis dropped. - 02Adopt it where it's neededAdd it to a shadow root's or the page's
adoptedStyleSheetswithpush(), and know it comes after the root's own<style>sheets. - 03Share one sheet and change it onceGive every copy of a component the same sheet object, and restyle every copy with one call.
What are constructable stylesheets?
Leaf and Kettle's menu page shows three tea cards. In lesson 11.1, each card carried its own <style>. For two cards, the browser printed Same sheet? false. Each card had a sheet of its own.
Now Asha wants a night menu. One click should turn every card gold. With a <style> in each card, she would have to change three sheets. Can the cards share one sheet, and can she change it once?
Yes. A constructable stylesheet is a style sheet you create in JavaScript, with new CSSStyleSheet(). You fill it with CSS using replaceSync() or replace(). Then you add it to a shadow root's adoptedStyleSheets list. Every root that adopts it shares one sheet, so one change restyles them all.
Here are Asha's three cards, sharing one sheet:
<tea-card>Green tea</tea-card><tea-card>Oolong</tea-card><tea-card>Black tea</tea-card><script src="tea-card.js"></script><script> const cards = [...document.querySelectorAll("tea-card")]; const sheets = cards.map((card) => card.shadowRoot.adoptedStyleSheets[0]); console.log("Same sheet?", sheets.every((sheet) => sheet === sheets[0]));</script>- In the
tea-card.jstab, line 1 makes an empty style sheet.CSSStyleSheetis the browser's object for a style sheet. A<style>element makes the same kind of object for you. - Line 2 fills it with one rule: bold, sea green text. Lines 1 and 2 sit at the top of the file, outside the class. So they run once, when the file loads.
- Line 7 attaches the card's shadow root. Line 8 gives the root the sheet, in a list called
adoptedStyleSheets. To adopt a sheet is to put it in that list. - Line 9 puts a paragraph with a slot in the root.
- Back in the page, lines 1 to 3 are three cards. Line 7 takes the first adopted sheet from each card's root. Line 8 asks whether all three are the same object.
It prints Same sheet? true. All three names are bold and sea green. One sheet styles three shadow roots.
<style> makes a sheet of its own. On the right, all three cards adopt the same sheet, so there is one object to parse, keep, and change.Leaf and Kettle has three counters. The owner could photocopy the menu for each one. Then every price change means three new copies. Instead, she hangs one big printed board that all three counters can see. She changes the board once, and every counter reads the new menu.
- In real life: The printed menu board
- In JavaScript: One
CSSStyleSheet, made withnew CSSStyleSheet() - In real life: A photocopy at each counter
- In JavaScript: A
<style>in each shadow root - In real life: Each counter reading the one board
- In JavaScript: Each root listing the sheet in
adoptedStyleSheets - In real life: Writing a new menu on the board
- In JavaScript:
replaceSync()on the shared sheet
Make a sheet once with new CSSStyleSheet(), fill it with replaceSync(), and add it to each shadow root's adoptedStyleSheets. The roots share one sheet object. Change it, and every root that adopted it changes too.
The name comes from the constructor: you construct the sheet yourself. The CSSOM spec calls the result a constructed style sheet. Lesson 1.2 listed them among the features every browser has now. MDN marks them Baseline, widely available, as that lesson's support table does.
How do you create a stylesheet in JavaScript?
Call the constructor with new. You get an empty sheet. It isn't on the page yet, so it styles nothing. It's like a blank menu board, still in its wrapping.
A sheet keeps its rules in cssRules, a list of rule objects. Two methods change that list, one rule at a time:
insertRule(rule, index)adds a rule at a position. Leave out the position, and it goes first, at 0.deleteRule(index)takes out the rule at a position.
<p>Green tea</p><script> const sheet = new CSSStyleSheet(); console.log("Rules:", sheet.cssRules.length); sheet.insertRule("p { color: seagreen; }"); sheet.insertRule("p { font-weight: bold; }", 1); console.log("Rules:", sheet.cssRules.length); sheet.deleteRule(1); console.log("Rules:", sheet.cssRules.length); document.adoptedStyleSheets = [sheet];</script>- Line 3 makes the sheet. Line 4 prints
Rules: 0. - Line 5 adds a sea green rule at position 0. Line 6 adds a bold rule at position 1, after it.
- Line 7 prints
Rules: 2. - Line 8 takes out the rule at position 1, the bold one. Line 9 prints
Rules: 1. - Line 10 hands the sheet to the page itself. A document has an
adoptedStyleSheetslist too.
In the result, Green tea is sea green, but not bold. Line 8 took the bold rule out before the page adopted the sheet.
The media and disabled options
The constructor can take an object of options. Two of them are:
media, the media the sheet is for, like"print". It works like themediaattribute of a<link>.disabled. Set totrue, the sheet starts switched off.
<p>Green tea</p><script> const print = new CSSStyleSheet({ media: "print" }); print.insertRule("p { font-style: italic; }"); const bold = new CSSStyleSheet({ disabled: true }); bold.insertRule("p { font-weight: bold; }"); document.adoptedStyleSheets = [print, bold]; const p = document.querySelector("p"); console.log("Style:", getComputedStyle(p).fontStyle); console.log("Weight:", getComputedStyle(p).fontWeight); bold.disabled = false; console.log("Weight now:", getComputedStyle(p).fontWeight);</script>- Line 3 makes a sheet for print only. Line 4 gives it an italic rule.
- Line 5 makes a sheet that starts switched off. Line 6 gives it a bold rule.
- Line 7 adopts both. Line 9 prints
Style: normal, because a screen isn't print. Line 10 printsWeight: 400, because the bold sheet is off. - Line 11 switches it on. Line 12 prints
Weight now: 700.
When the page is printed, the print sheet applies, and Green tea is italic. Why it matters: disabled is a light switch. The sheet stays in the list, and its rules wait until you turn it on.
What is the difference between replace() and replaceSync()?
Adding rules one at a time is slow to write. Usually you have the whole CSS as text. Two methods take that text and swap in all its rules at once:
replaceSync(text)does it right away, and gives back nothing.replace(text)gives back a promise: an object for a result that comes later. The promise resolves with the same sheet. Promises covers them.
<p>Green tea</p><script type="module"> const sheet = new CSSStyleSheet(); document.adoptedStyleSheets = [sheet]; const p = document.querySelector("p"); console.log(sheet.replaceSync("p { color: seagreen; }")); console.log("After replaceSync:", getComputedStyle(p).color); const same = await sheet.replace("p { color: sienna; }"); console.log("Same sheet?", same === sheet); console.log("After replace:", getComputedStyle(p).color, sheet.cssRules.length);</script>- Line 2 makes this a module script, so line 10 can use
awaiton its own. async and await explainsawait. - Line 3 makes the sheet. Line 4 adopts it, while it's still empty.
- Line 7 calls
replaceSync()and prints what it gives back:undefined. - Line 8 prints
After replaceSync: rgb(46, 139, 87). The new rule works on the very next line. - Line 10 calls
replace(), andawaitwaits for its promise. - Line 11 prints
Same sheet? true. - Line 12 prints
After replace: rgb(160, 82, 45) 1. That's sienna, and one rule. The sea green rule is gone.
So both methods replace every rule. They never add to the old ones. And look at line 4 again. The page adopted the sheet while it was empty, and still changed with it. The page holds the sheet itself, not a copy.
At Leaf and Kettle, you can wait at the counter until your tea is ready. Or you can take a buzzer to your seat, and go back when it buzzes. Either way, you get the same tea.
- In real life: Waiting at the counter
- In JavaScript:
replaceSync(): the next line runs with the new rules in - In real life: The buzzer you take to your seat
- In JavaScript: The promise that
replace()gives back - In real life: The buzzer going off
- In JavaScript: The promise resolving with the sheet
- In real life: The same tea either way
- In JavaScript: The same rules in the same sheet
Which should you use? When the CSS is already a string in your file, replaceSync() is simplest. The sheet is ready before the next line runs. replace() fits code that already uses await. The CSSOM spec lets a browser parse its text in parallel. Chromium's code parses it at once and hands back a promise that has already resolved.
Read each row across: a question, then the answer for each method.
| Question | replaceSync() | replace() |
|---|---|---|
| What does it give back? | Nothing: undefined. | A promise. It resolves with the same sheet. |
| When can you use the new rules? | On the very next line. | After the promise resolves, with await or then(). |
| What happens to the old rules? | Every one is replaced. | Every one is replaced. |
What happens to @import? | It's dropped, with a warning in the console. | It's dropped, with a warning in the console. |
| Which sheets accept it? | Only constructed sheets. | Only constructed sheets. |
Does @import work in a constructed stylesheet?
No. An @import rule loads another CSS file from inside a sheet. A constructed sheet drops every @import rule:
<p>Green tea</p><script> const sheet = new CSSStyleSheet(); sheet.replaceSync('@import url("fonts.css"); p { color: seagreen; }'); console.log("Rules:", sheet.cssRules.length); console.log(sheet.cssRules[0].cssText); try { sheet.insertRule('@import url("fonts.css");'); } catch (error) { console.log(error.name); }</script>- Line 4 passes two rules: an
@importand a sea green rule. - Line 5 prints
Rules: 1. Line 6 prints the rule that's left:p { color: seagreen; }. - Line 8 tries to add an
@importwithinsertRule(). That throws an error, and line 10 printsSyntaxError.
Open DevTools' Console to see one more line. Chrome prints a warning there: @import rules are not allowed here. The result's own console only shows what the page logs. The error from line 8 says Can't insert @import rules into a constructed stylesheet.
The CSSOM spec tells both methods to remove every @import, and MDN notes the warning. An earlier draft let replace() load imports. web.dev's article says Chrome stopped loading them in Chrome 84.
Why it matters: a constructed sheet never loads another file. To bring CSS in from a file, lesson 11.6, CSS module scripts, imports it. import sheet from "./tea.css" with { type: "css" } gives you a ready-made CSSStyleSheet.
How does adoptedStyleSheets work?
Every shadow root has an adoptedStyleSheets property, and so does every document. Lesson 9.4 listed it among the members the two share. So getRootNode() finds the right list from any node.
The property holds an array of constructed sheets. You can set a whole new array, as the cards do with root.adoptedStyleSheets = [sheet]. Or you can change the array in place, with the array methods you know:
push(sheet)adds a sheet at the end;indexOf(sheet)finds where a sheet is, or gives-1;splice(index, 1)takes out the sheet at that position.
Click the button in the result a few times:
<tea-card>Green tea</tea-card><button>Add or remove the crimson sheet</button><script src="tea-card.js"></script><script> const root = document.querySelector("tea-card").shadowRoot; const crimson = new CSSStyleSheet(); crimson.replaceSync("p { color: crimson; }"); const show = () => { const color = getComputedStyle(root.querySelector("p")).color; console.log("Sheets:", root.adoptedStyleSheets.length, color); }; show(); document.querySelector("button").addEventListener("click", () => { const index = root.adoptedStyleSheets.indexOf(crimson); if (index === -1) root.adoptedStyleSheets.push(crimson); else root.adoptedStyleSheets.splice(index, 1); show(); });</script>- Line 1 is a card. Its
tea-card.jstab is the card from the first example, with one sea green sheet. - Line 5 gets the card's shadow root. Lines 6 and 7 make a crimson sheet.
- Lines 8 to 11 print how many sheets the root has, and the color of its paragraph. Line 12 prints
Sheets: 1 rgb(46, 139, 87). - Line 14 looks for the crimson sheet in the list.
- When it isn't there, line 15 pushes it. The result prints
Sheets: 2 rgb(220, 20, 60). - When it is there, line 16 splices it out. The result prints
Sheets: 1 rgb(46, 139, 87)again.
Each click changes the card at once. Taking a sheet out doesn't destroy it. It only leaves the list, ready to come back.
The tea shop keeps its recipes in a ring binder. Clip a new page in at the back, and the cooks read it last. Unclip it, and the page is still whole, just out of the binder. When two pages disagree, the cooks follow the one further back.
- In real life: The ring binder
- In JavaScript:
adoptedStyleSheets - In real life: Clipping a page in at the back
- In JavaScript:
push(sheet) - In real life: Unclipping a page
- In JavaScript:
splice(index, 1) - In real life: The page further back wins
- In JavaScript: A later sheet wins a tie
Why it matters: push() and splice() add or remove one sheet and leave the others alone. A new array replaces the whole list, even sheets that other code added. MDN notes that an earlier version of the spec froze the array. Changing it in place came later, so it needs Chrome 99 or later.
Do adopted sheets come before or after style elements?
After. The CSSOM spec builds each root's final list of sheets in two parts:
- the root's own sheets, from its
<style>and<link>elements, in the order they sit in the tree; - then its adopted sheets, in array order.
The sixth step of the cascade in lesson 11.4 was order of appearance. When two rules tie at every step before it, the later rule wins. So on a tie, an adopted sheet beats a <style> in the same root, wherever the <style> sits:
<tea-card>Green tea</tea-card><script src="tea-card.js"></script><script> const root = document.querySelector("tea-card").shadowRoot; console.log("styleSheets:", root.styleSheets.length); console.log("adoptedStyleSheets:", root.adoptedStyleSheets.length); console.log("Color:", getComputedStyle(root.querySelector("p")).color);</script>- In the
tea-card.jstab, line 2 is the adopted sheet's rule: sea green. - Line 9 puts a
<style>in the root, after the paragraph. It asks for crimson. It arrives after line 8 adopted the sheet. - Back in the page, line 5 prints
styleSheets: 1. That list only holds the<style>'s sheet. - Line 6 prints
adoptedStyleSheets: 1. Line 7 printsColor: rgb(46, 139, 87).
Sea green wins. The <style> comes later in the markup, and it was added later. Neither one matters. Adopted sheets always come after.
<style> sheets come first, wherever the <style> sits. Adopted sheets come after them. Both rules here are p, so the later one, sea green, wins.Order only settles ties. Press Edit & run and change the <style>'s selector on line 9 to p:first-child. It scores 0-1-1, more than p. Now the page prints Color: rgb(220, 20, 60). Specificity is step 5, so it comes before order.
Adopting a sheet on the page
document.adoptedStyleSheets works the same way for the page's own elements. The first examples in this lesson used it. MDN says a document's adopted sheets come after its styleSheets too. And they stay out of document.styleSheets, as a root's stay out of its styleSheets. One sheet can sit in the page's list and in a shadow root's list at once. Exercise 5 uses that.
How do you update a shared stylesheet?
Change the sheet itself. Every root that adopted it uses the change, because they all hold the same object. Here is Asha's night menu. Press Night menu in the result:
<tea-card>Green tea</tea-card><tea-card>Oolong</tea-card><tea-card>Black tea</tea-card><button>Night menu</button><script src="tea-card.js"></script><script> const cards = [...document.querySelectorAll("tea-card")]; const colors = () => cards.map((card) => getComputedStyle(card.shadowRoot.querySelector("p")).color).join(", "); console.log("Day:", colors()); document.querySelector("button").addEventListener("click", () => { customElements.get("tea-card").theme.replaceSync("p { color: gold; background: black; }"); console.log("Night:", colors()); });</script>- In the
tea-card.jstab, lines 1 and 2 make the theme sheet, sea green. - Line 5 is a static field. It puts the sheet on the class itself, as
TeaCard.theme. Static members covers them. Line 10 adopts the sheet in every card. - In the page, line 4 is the button. Line 10 prints the three colors at the start:
Day: rgb(46, 139, 87), rgb(46, 139, 87), rgb(46, 139, 87). - Line 12 gets the class with
customElements.get("tea-card"). Then it replaces the theme's rules. - Line 13 prints
Night: rgb(255, 215, 0), rgb(255, 215, 0), rgb(255, 215, 0). That's gold, three times, on black.
One call changed three cards. With a <style> in each card, you would loop over the cards and change every <style>.
replaceSync() swaps every rule in the one sheet. Every card adopted that same sheet, so the Night menu button changes all three at once.Leaf and Kettle plays music in every room from one playlist. When the manager picks a new song, every speaker plays it at once. Nobody walks from room to room to change it.
- In real life: The playlist
- In JavaScript: The shared theme sheet
- In real life: A speaker in each room
- In JavaScript: Each card's shadow root
- In real life: Picking a new song
- In JavaScript:
theme.replaceSync(...) - In real life: Every room hears it at once
- In JavaScript: Every card restyles
How does the browser know which roots to update? Chromium's CSSStyleSheet::DidMutate goes through every tree that adopted the sheet. It marks each one for a style update. insertRule() and deleteRule() change the sheet too. The playground's button used insertRule(), and all three shared cards turned sienna.
Why it matters: a theme switch, a dark mode, or a new brand color becomes one call. In a real kit, the theme sheet would live in a module of its own, and every component would import it. Lesson 12.6, in Styling web components, organizes shared sheets like this across a whole library.
Can an iframe use a constructed stylesheet?
Not the page's sheet. A constructed sheet remembers the document whose window made it. The spec calls that its constructor document. When you add a sheet to an adoptedStyleSheets list, the CSSOM spec checks two things:
- the sheet must be a constructed one;
- its constructor document must be the document the list belongs to.
If either check fails, it throws a NotAllowedError. Every shadow root on the page belongs to the page's document, so any of them can adopt the page's sheets. A second document can't. Here, document.implementation.createHTMLDocument() makes a second, empty document in memory:
<p>Green tea</p><script> const sheet = new CSSStyleSheet(); sheet.replaceSync("p { color: seagreen; }"); document.adoptedStyleSheets.push(sheet); console.log("This page: adopted"); const other = document.implementation.createHTMLDocument(); try { other.adoptedStyleSheets.push(sheet); } catch (error) { console.log(`${error.name}: ${error.message}`); }</script>- Lines 3 to 5 make a sheet and adopt it on the page. Line 6 prints
This page: adopted. - Line 8 makes a second document.
- Line 10 tries to push the same sheet into its list. That throws.
- Line 12 prints
NotAllowedError: Sharing constructed stylesheets in multiple documents is not allowed.
That's Chrome's message for the second check. The first check has its own: pushing the sheet of a <style> element throws NotAllowedError: Can't adopt non-constructed stylesheets.
An iframe holds a document of its own, so the same rule applies. MDN gives a frame as its example. To style an iframe's page, make the sheet with the iframe's own window:
const frame = document.querySelector("iframe");
const frameDocument = frame.contentDocument;
// frameDocument.adoptedStyleSheets.push(sheet) would throw a NotAllowedError.
const frameSheet = new frame.contentWindow.CSSStyleSheet();
frameSheet.replaceSync("p { color: seagreen; }");
frameDocument.adoptedStyleSheets.push(frameSheet);- Lines 1 and 2 find the iframe and its document.
- Line 4 is the line that would fail. The page's
sheetbelongs to the page. - Line 5 calls the
CSSStyleSheetof the iframe's window. That sheet belongs to the iframe's document. - Lines 6 and 7 fill it and adopt it there.
Try this one on a page of your own. The results on this page run in sandboxed frames, and a sandboxed frame can't reach the document of a frame inside it.
Every book in the town library has the library's stamp inside. You can read it in any reading room of that library. Take it to the school library, and the desk says no, because the stamp is wrong. The school needs a copy of its own.
- In real life: A library
- In JavaScript: A document
- In real life: The stamp inside the book
- In JavaScript: The sheet's constructor document
- In real life: The library's reading rooms
- In JavaScript: The document's shadow roots
- In real life: The school library's desk saying no
- In JavaScript:
NotAllowedErrorfrom another document's list - In real life: The school's own copy
- In JavaScript:
new frame.contentWindow.CSSStyleSheet()
Why it matters: a component that draws into another window, like an iframe or a popup, can't take the page's sheet along. It needs a sheet made by that window.
Sharing one sheet across the tea kit's cards
Since lesson 7.1, the kit's tea-card builds its shadow root from one template. The template holds the card's <style>. So every card clones a <style> and gets a sheet of its own. This lesson's kit moves those rules into one constructed sheet.
<tea-card name="Green tea" price="4"></tea-card><tea-card name="Oolong" price="5"></tea-card><tea-card name="Black tea" price="3"></tea-card><script type="module"> import "./tea-kit/index.js"; const roots = [...document.querySelectorAll("tea-card")].map((card) => card.shadowRoot); const sheets = roots.flatMap((root) => [...root.styleSheets, ...root.adoptedStyleSheets]); console.log("Sheet objects:", new Set(sheets).size); console.log("Border:", getComputedStyle(roots[0].querySelector(".card")).borderColor);</script>Sheet objects: 3. Border: rgb(46, 139, 87). Each card's shadow root holds a <style> cloned from the template, so three cards hold three sheet objects.
- Lines 1 to 3 of the page are three kit cards. Line 5 loads the kit.
- Line 8 gathers every sheet in the three roots, from both lists. Line 9 counts the different objects. Line 10 prints the first card's border color.
With the kit from lesson 11.4, it prints Sheet objects: 3. With this lesson's kit, it prints Sheet objects: 1. Both print Border: rgb(46, 139, 87). The cards look the same.
const sheet = new CSSStyleSheet();
sheet.replaceSync(`
.card { border: 2px solid seagreen; border-radius: 8px; padding: 8px 12px; }
h3 { margin: 0; color: seagreen; }
p { margin: 4px 0 0; }
h4 { margin: 8px 0 0; }
.buy { display: flex; align-items: center; gap: 8px; margin-top: 8px; }
button { font: inherit; }
::slotted(p) { margin: 4px 0 0; }
`);- Line 1 makes the sheet, once, when the file first runs.
- Lines 2 to 10 fill it with the card's rules. They are the same seven rules the
<style>held, in the same order.
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.adoptedStyleSheets = [sheet];
this.shadowRoot.append(template.content.cloneNode(true));- Line 3 attaches the root. Line 4 adopts the shared sheet. Line 5 clones the template, which now holds only markup.
The card inside tea-panel adopts the same sheet, since the panel's shadow root is on the same page. Nothing else in the kit changes.
Lit works this way too. Its source turns each css block in a component's static styles into one constructed sheet, and adopts the sheets in each instance's root. Stage 8, Lit, covers it.
Common mix-ups
- "Each shadow root gets a copy of an adopted sheet." No. Every root holds the same object. A change to it shows in all of them.
- "I have to write
adoptedStyleSheets = [...old, sheet]." No. The array used to be frozen. Todaypush()andsplice()change it in place. - "
replaceSync()adds rules to the sheet." No. It replaces every rule, and so doesreplace(). UseinsertRule()to add one. - "
@importworks inreplace(), since it waits." No. Both methods drop every@import, with a warning in DevTools' Console. - "A
<style>added after the sheet wins." No. Adopted sheets come after the root's own sheets. Only a more specific rule beats them. - "
shadowRoot.styleSheetslists the adopted sheets." No. It lists the sheets of<style>and<link>elements. ReadadoptedStyleSheetsfor the rest. - "An iframe can adopt the page's sheet." No. A sheet belongs to the document whose window made it. Another document throws a
NotAllowedError. - "Adopted sheets need a polyfill." No. Chrome 73, Firefox 101, and Safari 16.4 support them.
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
What does the console print?
<script> const sheet = new CSSStyleSheet(); sheet.replaceSync("p { color: seagreen; } h3 { margin: 0; }"); sheet.replaceSync("p { color: sienna; }"); console.log(sheet.cssRules.length);</script>1. The first call puts in two rules. The second call replaces every rule with its own text, which holds one rule.
In the tea-card.js tab, a <style> asks for sienna, and two adopted sheets ask for sea green and crimson. What does the console print?
<tea-card>Green tea</tea-card><script src="tea-card.js"></script><script> const root = document.querySelector("tea-card").shadowRoot; console.log("Color:", getComputedStyle(root.querySelector("p")).color);</script>Color: rgb(220, 20, 60), crimson. The root's own <style> comes first, then the adopted sheets in array order. red is last, so it wins the tie.
The page prints Sheet objects: 2. Fix tea-card.js so the cards share one sheet. What does your fixed page print?
<tea-card>Green tea</tea-card><tea-card>Oolong</tea-card><script src="tea-card.js"></script><script> const roots = [...document.querySelectorAll("tea-card")].map((card) => card.shadowRoot); console.log("Sheet objects:", new Set(roots.map((root) => root.adoptedStyleSheets[0])).size);</script><tea-card>Green tea</tea-card><tea-card>Oolong</tea-card><script src="tea-card.js"></script><script> const roots = [...document.querySelectorAll("tea-card")].map((card) => card.shadowRoot); console.log("Sheet objects:", new Set(roots.map((root) => root.adoptedStyleSheets[0])).size);</script>The constructor runs once per card, so the starter made two sheets. Made at the top of the file, the sheet is made once, and both cards adopt it. The page prints Sheet objects: 1.
The page prints Defined: false, and the result shows an error. What is the error's name? Then fix tea-card.js.
<tea-card>Green tea</tea-card><script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); console.log("Defined:", card.matches(":defined"));</script><tea-card>Green tea</tea-card><script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); console.log("Defined:", card.matches(":defined"));</script>root.styleSheets[0] is the sheet of a <style> element, so replaceSync() throws a NotAllowedError, and the card never finishes its upgrade. The fix makes a constructed sheet and adopts it. Then the page prints Defined: true.
The page's price is italic, but the card's price isn't. Make one sheet style both, without a second sheet. What does your fixed page print?
<p class="price">Price: 4</p><tea-card>Price: 5</tea-card><script> const brand = new CSSStyleSheet(); brand.replaceSync(".price { font-style: italic; }"); document.adoptedStyleSheets.push(brand); class TeaCard extends HTMLElement { constructor() { super(); const root = this.attachShadow({ mode: "open" }); root.innerHTML = '<p class="price"><slot></slot></p>'; } } customElements.define("tea-card", TeaCard); const inner = document.querySelector("tea-card").shadowRoot.querySelector(".price"); console.log(getComputedStyle(document.querySelector(".price")).fontStyle, getComputedStyle(inner).fontStyle);</script><p class="price">Price: 4</p><tea-card>Price: 5</tea-card><script> const brand = new CSSStyleSheet(); brand.replaceSync(".price { font-style: italic; }"); document.adoptedStyleSheets.push(brand); class TeaCard extends HTMLElement { constructor() { super(); const root = this.attachShadow({ mode: "open" }); root.adoptedStyleSheets.push(brand); root.innerHTML = '<p class="price"><slot></slot></p>'; } } customElements.define("tea-card", TeaCard); const inner = document.querySelector("tea-card").shadowRoot.querySelector(".price"); console.log(getComputedStyle(document.querySelector(".price")).fontStyle, getComputedStyle(inner).fontStyle);</script>Page rules don't reach into a shadow root, so the card's price stayed normal. Pushing the same brand sheet into the root's list styles both. The page prints italic italic.
The page makes 1,000 cards and prints Sheet objects: 1000. Change tea-card.js so every card shares one sheet. What does your fixed page print? Then record both versions in DevTools' Performance panel and compare the style work on your machine.
<div id="menu"></div><script src="tea-card.js"></script><script> const menu = document.querySelector("#menu"); for (let i = 1; i <= 1000; i++) { const card = document.createElement("tea-card"); card.textContent = `Tea ${i}`; menu.append(card); } const roots = [...menu.children].map((card) => card.shadowRoot); const sheets = roots.flatMap((root) => [...root.styleSheets, ...root.adoptedStyleSheets]); console.log("Sheet objects:", new Set(sheets).size);</script><div id="menu"></div><script src="tea-card.js"></script><script> const menu = document.querySelector("#menu"); for (let i = 1; i <= 1000; i++) { const card = document.createElement("tea-card"); card.textContent = `Tea ${i}`; menu.append(card); } const roots = [...menu.children].map((card) => card.shadowRoot); const sheets = roots.flatMap((root) => [...root.styleSheets, ...root.adoptedStyleSheets]); console.log("Sheet objects:", new Set(sheets).size);</script>With a <style> in each card, the page held 1,000 sheet objects. With one adopted sheet, it holds one. The page prints Sheet objects: 1.
Check your understanding
For each question, ask: is this one sheet object, or a copy? And which list is it in?
Question 1 of 7What does this page print after
await sheet.replace(...)?Read the code, then predict<script type="module"> const sheet = new CSSStyleSheet(); const result = await sheet.replace("p { color: seagreen; }"); console.log(result === sheet); </script>Choose an answer to see the explanation.
Question 2 of 7How many rules does this sheet have after the
@importline?Read the code, then predict<script> const sheet = new CSSStyleSheet(); sheet.replaceSync('@import url("tea.css"); h3 { margin: 0; } p { color: seagreen; }'); console.log(sheet.cssRules.length); </script>Choose an answer to see the explanation.
Question 3 of 7What does this page print for a root that only adopts a sheet?
Read the code, then predict<tea-card></tea-card> <script> const sheet = new CSSStyleSheet(); const root = document.querySelector("tea-card").attachShadow({ mode: "open" }); root.adoptedStyleSheets.push(sheet); console.log(root.styleSheets.length, root.adoptedStyleSheets.length); </script>Choose an answer to see the explanation.
Question 4 of 7A shadow root has a
<style>and an adopted sheet. Both setp { color: ... }. Which one wins?Choose an answer to see the explanation.
Question 5 of 7Three tea cards adopted the same sheet. What happens when you call
replaceSync()on it?Choose an answer to see the explanation.
Question 6 of 7A page pushes its own constructed sheet into an iframe's
document.adoptedStyleSheets. What happens?Choose an answer to see the explanation.
Question 7 of 7Why does older code write
root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet]?Choose an answer to see the explanation.
Key takeaways
- A constructable stylesheet is a
CSSStyleSheetyou make in JavaScript, withnew CSSStyleSheet(). replaceSync()swaps in every rule at once and gives back nothing.replace()does the same and gives back a promise of the sheet. Both drop@import.insertRule()anddeleteRule()change one rule at a time.- A shadow root's or a document's
adoptedStyleSheetslists the constructed sheets it uses. Change it withpush()andsplice(). - Adopted sheets come after the root's own
<style>and<link>sheets, andstyleSheetsdoesn't list them. - Make the sheet once, at the top of the component's file. Every copy shares it, and one change restyles them all.
- A sheet can only be adopted in the document whose window made it.
Remember the one-liner.
Make the sheet once, adopt it everywhere, and change it in one place.
Sources
The facts on this page come from these standards, docs, and source files:
- CSSOM: the CSSStyleSheet() constructor, CSS Working Group.
- CSSOM: replace() and replaceSync(), CSS Working Group.
- CSSOM: adoptedStyleSheets, CSS Working Group.
- CSSOM: the final CSS style sheets of a document or shadow root, CSS Working Group.
- CSSStyleSheet() constructor, MDN.
- CSSStyleSheet: replace() method, MDN.
- CSSStyleSheet: replaceSync() method, MDN.
- ShadowRoot: adoptedStyleSheets property, MDN.
- Document: adoptedStyleSheets property, MDN.
- Constructable stylesheets, Jason Miller, web.dev.
- CSSStyleSheet::DidMutate (css_style_sheet.cc, Chromium 158.0.8127.18), Chromium.
- Lit's css-tag.ts (lit@3.3.3), Lit.
Coming next: CSS module scripts. It imports a .css file as a ready-made style sheet.