Course contentsShow
← Web Development
Lesson 2463 of 2,98244. Web ComponentsFree lesson

Style Encapsulation in Shadow DOM

How styles defined inside shadow DOM are scoped and isolated from the main document.

Style Encapsulation in Shadow DOM

You'll learn how Shadow DOM creates a protective style boundary that keeps your component's CSS isolated from the rest of the page.

The Core Idea

When you define styles inside a shadow root, those styles are scoped exclusively to elements within that shadow tree. They don't leak out to affect the main document, and conversely, most styles from the main document won't penetrate into the shadow DOM. This is automatic style encapsulation—the browser enforces it for you.

Think of Shadow DOM like a soundproof recording booth. Musicians inside can make as much noise as they want without disturbing the office outside, and office chatter doesn't interfere with the recording. Similarly, your component's styles stay contained, and global stylesheets won't accidentally break your component's appearance.

How It Works

When you attach a shadow root and add styles inside it, those styles apply only to the shadow tree:

class MyCard extends HTMLElement {
  connectedCallback() {
    const shadow = this.attachShadow({ mode: 'open' });
    
    shadow.innerHTML = `
      <style>
        p { color: blue; font-size: 20px; }
      </style>
      <p>This paragraph is blue</p>
    `;
  }
}
customElements.define('my-card', MyCard);

Even if the main document has p { color: red; }, the paragraph inside <my-card> remains blue. The main document's p elements stay red. Each lives in its own style universe.

This isolation means you can write simple selectors without fear of conflicts, use common class names, and build truly reusable components.

Key Takeaway: Shadow DOM automatically creates a style boundary—styles defined inside shadow roots are scoped to that shadow tree and won't affect or be affected by external stylesheets, enabling true component-level encapsulation.