Allow injecting CSS rules from a specified attribute into the shadow DOM of elements.
npm install @glowingblue-dev/shadow-css

Injects custom CSS into open shadow roots via HTML attributes with optional runtime watching for attribute changes or newly added nodes.
- Add inline CSS or external .css files into open shadow roots
- Works with one or multiple attributes
- Optional live watching via MutationObserver: React to attribute changes and dynamically added nodes
- Zero dependencies, tiny footprint
``bash`
npm install @glowingblue-dev/shadow-css
or
`bash`
yarn add @glowingblue-dev/shadow-css
Assuming an unstyleable third party WebComponent with an open shadow DOM like:
`html`
`html`
`js
import $shadowCSS from "@glowingblue-dev/shadow-css";
$shadowCSS("data-css");
`
`html`
`js`
$shadowCSS("data-css", { watch: true });
`html`
data-css=".classname { color: red; }"
>
`js`
$shadowCSS(["data-theme", "data-css"], { watch: true });
`ts`
$shadowCSS(attrs?: string | string[], options?: { watch?: boolean }, target?: Node): MutationObserver
- attrs — one or more attribute names (default: "data-css").true
- options.watch — if , sets up a MutationObserver to update when the attribute value changes or when new elements with the attribute are added.document
- options.target - The target node to to look for attributes and optionally observe, defaults to the global .
Always returns a MutationObserver instance, if watch: true it is already activated and observing the DOM and can be disabled by calling .disconnect() at any later point. If watch: false (default) you can activate it at a point of your choosing by calling .observe(. The default options are attached to the returned MutationObserver instance for convenience.
When using a shared stylesheet across multiple components, scope your rules with :host(...):
`css
:host(custom-element) .selector {
transform: rotate(180deg);
}
:host(custom-element) {
& .selector {
...;
}
&:hover .selector {
...;
}
}
`
- Only works with open shadow DOMs. Closed roots cannot be styled this way.
- Runs in browsers (relies on document`).
MIT © Glowing Blue AG
Originally authored by exside