Explain the concept of Shadow DOM in LWC and how it enforces component encapsulation and styling isolation.
Answer
Basics: Without encapsulation, one component's .title { color: red; } could restyle every .title on the page, and global document.querySelector calls could reach into any component. Shadow DOM solves this with a boundary (the shadow root). Inside it, selectors and DOM queries only see that component's own elements. Each component has a host element (<c-my-comp>) and a shadow tree under it.
How it works:
- The component's template renders into its shadow root, reachable in code as
this.template. - Use
this.template.querySelector('.x')to find elements in your own template.document.querySelectorcannot see inside. - The component's CSS file is scoped: rules apply only to this template's elements (use
:hostto style the host element itself). - Parent CSS cannot reach into a child's shadow tree. Parents can only influence children through public properties, slots, or CSS custom properties (styling hooks), which do inherit across the boundary.
- Events cross the boundary according to
bubblesandcomposed. By default a custom event does neither, so only a direct listener on the element sees it.
Advanced / deep dive: Salesforce shipped synthetic shadow (a polyfill) so LWC could work with older browsers and with Aura, third-party scripts and global SLDS. Differences from native shadow: global stylesheets such as SLDS still apply inside synthetic shadow trees, while with native shadow they do not and styles must be supplied by the component or through styling hooks. Salesforce has been moving toward native shadow in some contexts, so treat the exact status per release as "verify in current release notes". Lightning Web Security and Lightning Locker also add a separate isolation layer between namespaces for scripting. Light DOM is the opt-out: a component can set and on its root template, which removes the shadow boundary so global CSS and work. Light DOM is available in a subset of contexts (notably Experience Cloud), so verify where you intend to use it. Light DOM trades encapsulation for easier theming and third-party integration.