Skip to content

Instantly share code, notes, and snippets.

@imamkhaira
Created October 14, 2025 04:44
Show Gist options
  • Select an option

  • Save imamkhaira/03d8474af3922dcc3e0cf778cc83d275 to your computer and use it in GitHub Desktop.

Select an option

Save imamkhaira/03d8474af3922dcc3e0cf778cc83d275 to your computer and use it in GitHub Desktop.
Create a single combined CSSStyleSheet from global styles. Convenient to add global styles to Shadow DOM.
export const combiledStyleSheet = new CSSStyleSheet();
const allRules = [...document.styleSheets]
.flatMap((ss) => {
try {
return [...ss.cssRules].map((rule) => rule.cssText);
} catch {
return []; // Skip cross-origin stylesheets
}
})
.filter(Boolean);
combiledStyleSheet.replaceSync(allRules.join(""));
@imamkhaira
Copy link
Author

Example on how to use with Web Component:

class TestComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.adoptedStyleSheets = [combiledStyleSheet];
  }

  connectedCallback() {
    // .bg-red is from the global CSS (tailwind or whatever)
    this.innerHTML = `<h1 class="bg-red">Test</h1>`;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment