completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Constructable stylesheets

Learn constructable stylesheets: make a CSSStyleSheet in JavaScript, fill it with replaceSync(), and share it with every shadow root via adoptedStyleSheets.

By the end, you can
  • 01
    Make a sheet in JavaScriptCreate one with new CSSStyleSheet(), fill it with replaceSync() or replace(), and know why @import is dropped.
  • 02
    Adopt it where it's neededAdd it to a shadow root's or the page's adoptedStyleSheets with push(), and know it comes after the root's own <style> sheets.
  • 03
    Share 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:

Three cards that adopt one shared sheetPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, line 1 makes an empty style sheet. CSSStyleSheet is 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.

Two halves. The left half is a style element in each root. Three cards, Green tea, Oolong, and Black tea, each have a sheet of their own, with an arrow from it to the card. It is labelled three sheet objects. The right half is one adopted sheet: the same three cards, and one sheet with an arrow to each card. It is labelled one sheet object.a <style> in each rootGreen teasheet 1Oolongsheet 2Black teasheet 3three sheet objectsone adopted sheetGreen teaOolongBlack teasheetone sheet object
On the left, each card's <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.
Real-life analogyOne printed menu board for every counter

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 with new 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
The main idea

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.
Make a sheet and change its rules one at a timePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 adoptedStyleSheets list 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 the media attribute of a <link>.
  • disabled. Set to true, the sheet starts switched off.
A sheet for print, and a sheet that starts switched offPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 prints Weight: 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.
replaceSync() and replace() on the same sheetPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 makes this a module script, so line 10 can use await on its own. async and await explains await.
  • 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(), and await waits 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.

Real-life analogyWaiting at the counter, or taking a buzzer

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.

replaceSync() and replace(), side by side
QuestionreplaceSync()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:

An @import rule in a constructed sheetPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 4 passes two rules: an @import and 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 @import with insertRule(). That throws an error, and line 10 prints SyntaxError.

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:

Add and remove a sheet on a card's rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 is a card. Its tea-card.js tab 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.

Real-life analogyPages in a ring binder

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:

  1. the root's own sheets, from its <style> and <link> elements, in the order they sit in the tree;
  2. 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:

A style element and an adopted sheet in one rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, 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 prints Color: 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.

The card's shadow root reads its sheets in order, top to bottom, with an arrow down the side labelled later. First the root's own style element, p { color: crimson; }, listed in styleSheets. Then adoptedStyleSheets[0], p { color: seagreen; }. Under them: same specificity, so the later rule wins: seagreen.the card's shadow root, first to lastlaterp { color: crimson; }the <style>, in styleSheetsp { color: seagreen; }adoptedStyleSheets[0]a tie on specificity: the later one wins
The root's own <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 share one stylesheet between web components?

Make the sheet once, at the top of the component's file, and adopt it in every constructor. That's the pattern from the first example. It's the same idea as the template in lesson 7.1, made once and cloned into each card.

Try both ways with the same three cards. In each one, press Change the first card's sheet in the result:

Playground: one sheet or three
Three cards, and a button that changes only the first card's sheetPop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card><tea-card>Oolong</tea-card><tea-card>Black tea</tea-card><button>Change the first card's sheet</button><script src="tea-card.js"></script><script>  const roots = [...document.querySelectorAll("tea-card")].map((card) => card.shadowRoot);  const sheetOf = (root) => root.adoptedStyleSheets[0] ?? root.styleSheets[0];  console.log("Sheet objects:", new Set(roots.map(sheetOf)).size);  document.querySelector("button").addEventListener("click", () => {    sheetOf(roots[0]).insertRule("p { color: sienna; }", 1);    const colors = roots.map((root) => getComputedStyle(root.querySelector("p")).color);    console.log("Sienna cards:", colors.filter((color) => color === "rgb(160, 82, 45)").length);  });</script>
ResultLoading…
Try it yourself
Three cards, three sheets.

Sheet objects: 3. After one click: Sienna cards: 1. Each card's <style> makes a sheet of its own. Press the button in the result: the new rule goes into the first card's sheet, so only Green tea turns sienna.

The page stays the same. Each choice swaps the tea-card.js tab. Press Change the first card's sheet in the result, then switch.
  • A <style> in each card: Sheet objects: 3. After the click, Sienna cards: 1.
  • One shared sheet: Sheet objects: 1. After the click, Sienna cards: 3.

Line 8 of the page finds each card's sheet: the adopted one, or else the <style>'s. Line 9 counts the different objects with a Set, which keeps one of each value. Map and Set covers it. Line 11 adds a sienna rule to the first card's sheet only.

With a <style> in each card, the first card's sheet is its own. The other two keep theirs. With one shared sheet, the first card's sheet is every card's sheet.

What does one object save? With a <style> in each root, every card gets a <style> element and a sheet object. Lesson 6.4 counted one sheet per card. Browsers can share the parsed rules behind <style> elements with the same text, as lesson 11.1 said. A constructed sheet makes the sharing yours to see and control. Your code parses the CSS once, with one replaceSync(), and every card holds the same object.

Exercise 6 makes a thousand cards each way. Record both in DevTools' Performance panel, and compare the style work on your own machine.

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:

One replaceSync() restyles every cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, 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>.

A window titled theme holds the shared sheet. Its old rule, p { color: seagreen; }, is crossed out. Its new rule is p { color: gold; background: black; }. Under it: one replaceSync() call. Three arrows go from the sheet to three cards, Green tea, Oolong, and Black tea, labelled all three turn gold.themep { color: seagreen; }p { color: gold; background: black; }one replaceSync() callGreen teaOolongBlack teaall three turn gold
replaceSync() swaps every rule in the one sheet. Every card adopted that same sheet, so the Night menu button changes all three at once.
Real-life analogyOne playlist for every speaker

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:

A second document refuses the page's sheetPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

Give an iframe a sheet made by its own windowJavaScript
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 sheet belongs to the page.
  • Line 5 calls the CSSStyleSheet of 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.

Two windows, one above the other. The top window, page, holds a sheet, labelled made here, adopted here. An arrow goes down from it toward the bottom window, iframe, labelled push(sheet) into the iframe: NotAllowedError. The iframe window holds frameSheet, labelled made by the iframe's window, adopted here.pagesheetmade here, adopted herepush(sheet) into the iframe: NotAllowedErroriframeframeSheetmade by the iframe's window, adopted here
The page's sheet works in the page and in every shadow root on it. The iframe's document refuses it, and takes a sheet made by the iframe's own window instead.
Real-life analogyA library book carries its library's stamp

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: NotAllowedError from 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.

Playground: the kit's cards, before and after
Three kit cards, counting their sheet objectsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
One sheet per card.

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.

The page stays the same. Only the kit changes: open the tea-kit/tea-card.js tab to see where the styles live.
  • 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.

The kit card's shared sheet (tea-kit/tea-card.js, lines 3 to 12)JavaScript
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.
The card's constructor (tea-kit/tea-card.js, lines 53 to 57)JavaScript
  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. Today push() and splice() change it in place.
  • "replaceSync() adds rules to the sheet." No. It replaces every rule, and so does replace(). Use insertRule() to add one.
  • "@import works in replace(), 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.styleSheets lists the adopted sheets." No. It lists the sheets of <style> and <link> elements. Read adoptedStyleSheets for 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.

Exercise 1 · Warm-upTwo replaceSync() calls in a row

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>
ResultLoading…

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

    Exercise 2 · Warm-upA style element and two adopted sheets

    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>
    ResultLoading…

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

      Exercise 3 · PracticeEvery card makes its own sheet

      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>
      ResultLoading…

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

        Exercise 4 · PracticereplaceSync() on a style element's sheet

        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>
        ResultLoading…

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

          Exercise 5 · ChallengeOne sheet for the page and the card

          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>
          ResultLoading…

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

            Exercise 6 · ChallengeA thousand cards

            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>
            ResultLoading…

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

              Check your understanding

              For each question, ask: is this one sheet object, or a copy? And which list is it in?

              The constructable stylesheets quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does this page print after await sheet.replace(...)?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              2. Question 2 of 7How many rules does this sheet have after the @import line?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              3. Question 3 of 7What does this page print for a root that only adopts a sheet?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              4. Question 4 of 7A shadow root has a <style> and an adopted sheet. Both set p { color: ... }. Which one wins?

                Choose an answer to see the explanation.

              5. 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.

              6. 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.

              7. 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 CSSStyleSheet you make in JavaScript, with new 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() and deleteRule() change one rule at a time.
              • A shadow root's or a document's adoptedStyleSheets lists the constructed sheets it uses. Change it with push() and splice().
              • Adopted sheets come after the root's own <style> and <link> sheets, and styleSheets doesn'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:

              Coming next: CSS module scripts. It imports a .css file as a ready-made style sheet.

              CompleteFrontend Clear concepts. Working examples.