Lesson 36 of 55
HTMLWeb Components – Shadow DOM
10 min
Course progress65%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 36 of 55
HTML10 min
Keep these ideas in mind as you work through the lesson.
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>
: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.attachShadow) with open or closed mode? ✅:host and ::slotted selectors for styling? ✅::part used where external styling is needed? ✅Tip: Use
:host-context()to style a component based on its surrounding context (e.g., dark‑mode detection).