Adopted Stylesheets — Complete Guide
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Adopted Stylesheets. We cover key concepts, practical examples, and best practices to help you master this topic.
Adopted stylesheets (adoptedStyleSheets) allow sharing CSSStyleSheet objects across shadow roots for efficient, reusable styles without duplication.
What You'll Learn
- How to create and use adopted stylesheets
- How to share styles across multiple component instances
- How adopted stylesheets improve performance
Why It Matters
Without adopted stylesheets, each component instance duplicates style Parsing. Adopted stylesheets parse once and share across instances.
flowchart LR A[CSSStyleSheet] --> B[Instance 1] A --> C[Instance 2] A --> D[Instance 3] B --> E[Shared styles]
Creating Adopted Stylesheets
// Create once, share across instances
const sharedStyles = new CSSStyleSheet();
sharedStyles.replaceSync(`
:host { display: block; font-family: sans-serif; }
.card { border: 1px solid #ddd; border-radius: 8px; padding: 16px; }
.card h3 { margin: 0 0 8px; color: #333; }
.card p { margin: 0; color: #666; }
`);
class SharedCard extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.adoptedStyleSheets = [sharedStyles];
this.shadowRoot.innerHTML = '<div class="card"><slot></slot></div>';
}
}
customElements.define('shared-card', SharedCard);
Dynamic Stylesheets
class DynamicTheme extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._sheet = new CSSStyleSheet();
this.shadowRoot.adoptedStyleSheets = [this._sheet];
this._updateTheme();
}
setTheme(colors) {
this._sheet.replaceSync(`
:host { --bg: ${colors.bg}; --text: ${colors.text}; }
.box { background: var(--bg); color: var(--text); padding: 16px; border-radius: 8px; }
`);
}
_updateTheme() {
this.setTheme({ bg: '#3498db', text: 'white' });
this.shadowRoot.innerHTML = '<div class="box"><slot></slot></div>';
}
}
customElements.define('dynamic-theme', DynamicTheme);
Common Mistakes
- Creating new stylesheet instances for each component instead of sharing
- Using replace() instead of replaceSync() without await
- Not checking browser support (Safari 15.4+)
Practice Questions
- How do adopted stylesheets improve performance? Styles are parsed once and shared across instances.
- What method replaces stylesheet content? replaceSync() for synchronous or replace() for async.
Mini Project
Build a component library where all components share a base stylesheet via adopted stylesheets. Each component adds its own specific styles.
What's Next
Lesson 17: Polyfills and Browser Support
← Previous
Component Communication — Complete Guide
Next →
Polyfills and Browser Support — Complete Guide
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro