liveBook · Manning

Constructable stylesheet

As explained in Vanilla Web

A constructible stylesheet is a programmatically created CSSStyleSheet that can be adopted and shared by document or shadow roots.

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

How Vanilla Web covers it

How deep it goes
Defines stylesheet creation, population, and adoption, but does not detail compatibility or failure handling.
Examples
Shows a document-level accent stylesheet and shared stylesheets adopted by a shadow root.
What you can do after
Apply it via CSSStyleSheet and adoptedStyleSheets to share and dynamically update component styles.
How it connects
Connects CSSOM, shadow DOM, and CSS custom properties as related approaches to styling from JavaScript.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.