adoptedStyleSheets Share Constructable Styles
constructable CSSStyleSheet objects are adopted by document and shadow roots at once, so replaceSync updates and un-adoption apply everywhere simultaneously.
Code
// A constructable stylesheet is one object serving many adopters
const sheet = new CSSStyleSheet();
sheet.replaceSync('p { border-width: 2px; border-style: solid; }');
const host = document.createElement('div');
document.body.append(host);
const root = host.attachShadow({ mode: 'open' });
root.innerHTML = '<p>in shadow</p>';
const lightP = document.createElement('p');
document.body.append(lightP);
// The same sheet instance is adopted by the document and the shadow root
document.adoptedStyleSheets = [sheet];
root.adoptedStyleSheets = [sheet];
const shadowP = root.querySelector('p');
console.log('light DOM p styled:', getComputedStyle(lightP).borderTopWidth === '2px');
console.log('shadow p styled:', getComputedStyle(shadowP).borderTopWidth === '2px');
// replaceSync rewrites the shared sheet; every adopter sees the update
sheet.replaceSync('p { border-width: 1px; border-style: solid; }');
console.log('update reached both adopters:',
getComputedStyle(lightP).borderTopWidth === '1px' &&
getComputedStyle(shadowP).borderTopWidth === '1px');
// Un-adoption removes its styles everywhere at once
document.adoptedStyleSheets = [];
root.adoptedStyleSheets = [];
console.log('removed everywhere:',
getComputedStyle(lightP).borderTopWidth === '0px' &&
getComputedStyle(shadowP).borderTopWidth === '0px');How it works
The demo data lives in module-level bindings: sheet, host, root, lightP.
Points of care
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
- Uses
document, so it needs a browser context — it will not run as-is in Node without shims.
Using it
Output lines are prefixed (light DOM p styled:, shadow p styled:, update reached both adopters:), making each step’s effect easy to spot.
Key statements
sheet.replaceSync('p { border-width: 2px; border-style: solid; }');
sheet.replaceSync('p { border-width: 1px; border-style: solid; }');
const root = host.attachShadow({ mode: 'open' });
Interactive Tools for This Topic
FAQ
- Does adoptedStyleSheets Share Constructable Styles run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.