what is shadow dom
Quick Scoop
Shadow DOM is a browser feature that lets web developers attach a separate, encapsulated DOM subtree to an element, so its HTML structure and CSS are isolated from the rest of the page.
In plain terms, it helps build self-contained componentsâlike custom buttons, video players, or widgetsâwithout their styles or internal markup leaking out or being accidentally affected by outside code.
How it works
- The main element is called the shadow host.
- The hidden subtree inside it is the shadow tree.
- The point where they meet is the shadow boundary.
- Styles inside the shadow tree are scoped, so they usually do not collide with page-wide CSS.
Why developers use it
- Encapsulation: Keeps component internals private and predictable.
- Style isolation: Prevents CSS conflicts with the rest of the page.
- Reusable components: Makes it easier to ship UI parts that work the same anywhere.
Simple example
Think of it like a âmini webpage inside a webpage.â A shopping-cart widget can have its own markup and styles, and the rest of the site wonât accidentally restyle its buttons or layout.
One caveat
Shadow DOM is great for isolation, but it can make debugging, styling from the outside, and some kinds of automation more complicated, especially when the shadow root is closed.
If you want, I can also show you a tiny code example of Shadow DOM in JavaScript.