Shadow DOM
Shadow DOM is a browser standard that lets developers attach an encapsulated, hidden DOM subtree to an element, keeping its internal structure, styles, and behavior isolated from the rest of the page.
Definition
Shadow DOM is a browser standard that lets developers attach an encapsulated, hidden DOM subtree to an element, keeping its internal structure, styles, and behavior isolated from the rest of the page.
Overview
Shadow DOM solves a long-standing problem in web development: CSS and DOM selectors are global by default, so styles and scripts written for one part of a page can accidentally affect — or be affected by — another. By attaching a 'shadow root' to an element, its internal markup and styles become encapsulated: CSS rules defined inside the shadow tree don't leak out, and outer page styles generally don't leak in, creating a genuinely self-contained component boundary. Shadow DOM is one of the three core Web Components standards, alongside Custom Elements (for defining new HTML tags) and HTML templates (for declarative, inert markup that can be cloned). Together they let developers build framework-agnostic, reusable UI components using only native browser APIs — no external library required — that behave like real HTML elements and can be dropped into any page regardless of what framework, if any, is used elsewhere on it. Browsers themselves have used shadow-DOM-like encapsulation internally for years — for example, a native `<video>` element's play/pause controls are rendered in a hidden internal tree the page can't accidentally restyle. Exposing this capability to developers made it possible to build design-system components, embeddable widgets, and third-party UI elements that won't be broken by, or break, the host page's styles. It's frequently used together with frameworks like Vue.js or Angular for scoped component styling under the hood, and libraries like Lit build directly on top of it.
Key Concepts
- Encapsulates a subtree of DOM and CSS from the rest of the page
- Prevents outer page styles from leaking into a component, and vice versa
- One of the three core Web Components standards alongside Custom Elements
- Enables truly framework-agnostic, reusable UI components
- Supports both 'open' and 'closed' modes controlling external JS access to the shadow tree
- Used natively by browsers for built-in elements like `<video>` controls
- Basis for component libraries like Lit