A constructable stylesheet is a CSSStyleSheet created in JavaScript, populated with CSS, then adopted by a document or shadow root. Sharing one sheet can keep component styles modular and avoid reparsing CSS for each component instance. section 6.2.12 section 7.8.4
Use this approach when CSS needs to be generated or shared programmatically:
- Create a CSSStyleSheet, set its content with replaceSync() or replace(), and add it to adoptedStyleSheets. section 7.8.4
- Prefer classes, data attributes, or CSS custom properties for ordinary state-driven styling; direct CSSOM rule manipulation can be fragile. section 6.2.12
const sheet = new CSSStyleSheet();
sheet.replaceSync(`
:root { --accent: #ff2d55 }
.card{ border-color: var(--accent) }
`);
document.adoptedStyleSheets = [...document.adoptedStyleSheets,
sheet];
Creates a stylesheet and adopts it at the document level. section 6.2.12
shadow.adoptedStyleSheets = [globalResetStyles, buttonStyles, mySpecificThemeStyles];
Combines shared stylesheets in a shadow root. section 7.8.4
