Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Web Components – Shadow DOM | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 36 of 55

·HTML

Web Components – Shadow DOM

10 min

Course progress65%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Attaching a shadow root with `attachShadow` (`open` vs. `closed` mode)
  • Using `<slot>` for content projection and composition
  • Styling with `:host`, `::slotted`, and `::part` selectors
  • Benefits of encapsulation and avoiding CSS name collisions
  • Advanced theming techniques (`:host-context`)

Shadow DOM Basics

The Shadow DOM creates a private subtree for a component, isolating its CSS and markup from the main document.

class Card extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `
      <style>
        :host { display: block; border: 1px solid #ccc; padding: 1rem; }
        h2 { margin: 0; color: teal; }
      </style>
      <h2><slot name='title'></slot></h2>
      <div><slot></slot></div>
    `;
  }
}
customElements.define('my-card', Card);
<my-card>
  <span slot='title'>Hello</span>
  This is the card content.
</my-card>

Styling hooks

  • :host – Styles the custom element itself from inside the shadow tree.
  • ::slotted(selector) – Styles content projected into a <slot>.
  • ::part(name) – Exposes internal parts for external styling.
  • ::theme – Future proposal for theming custom elements.

Benefits

  • Encapsulation – Prevents style leakage and name collisions.
  • Predictable styling – The component looks the same regardless of page CSS.
  • Scoping – Allows you to ship a component with its own stylesheet without polluting the global scope.

Quick checklist for Shadow DOM

  1. Shadow root attached (attachShadow) with open or closed mode? ✅
  2. Use of :host and ::slotted selectors for styling? ✅
  3. Slots defined for content projection? ✅
  4. ::part used where external styling is needed? ✅
  5. No unintended global CSS affecting the component? ✅

Tip: Use :host-context() to style a component based on its surrounding context (e.g., dark‑mode detection).

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonWeb Components – Custom ElementsContinue to lesson 37Performance – Lazy Loading Images & IframesBack to HTML Course curriculum