Scoped Styles Inside Shadow DOM
Write CSS that only affects elements within the shadow tree.
CSS Encapsulation by Default
Every <style> rule inside a shadow root applies only inside that root. p { color: red } in a shadow tree colors only paragraphs inside that shadow — paragraphs in the main document are unaffected, and main-document styles do not reach into the shadow.
Why Encapsulation Matters
Encapsulation eliminates the global-CSS problem that has haunted large applications for decades. A component's styles cannot be accidentally overridden by site CSS, and the component cannot break the site by accident. The boundary is the spec, not a convention.
All lessons in this course
- attachShadow and Shadow Root
- Slot Elements for Content Distribution
- Scoped Styles Inside Shadow DOM
- Part and Exportparts for External Styling