What is Shadow DOM in Web Development
Shadow DOM is browser technology that allows creating encapsulated DOM trees inside elements.
It isolates HTML, CSS and JS to avoid conflicts with external page styles and scripts.
Why Shadow DOM?
Encapsulation
Everything inside Shadow DOM is not directly accessible from outside: neither CSS styles nor JS code from outside affect component internals.
Style isolation
Styles written in Shadow DOM don't leak outside, and vice versa — external styles don't affect internal structure of component.
Component purity
Shadow DOM makes Web Components more reliable and independent from external environment.
How to Use Shadow DOM
Created via .attachShadow() method:
<div id="my-element"></div>
<script>
const host = document.getElementById("my-element");
const shadow = host.attachShadow({ mode: "open" });
shadow.innerHTML = ``;
</script>
mode: "open"— allows accessing shadowRoot from outside via JS.mode: "closed"— makes shadowRoot completely private.
Structure
- Custom Element — custom HTML tag (e.g.,
<my-modal>). - Shadow Root — root of isolated tree.
- Shadow DOM Tree — component content (internal HTML + styles).
- Light DOM — content passed inside tag as regular children.
Web Component Example
class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<style>p { color: blue; }</style>
<p>I'm in shadow</p>
`;
}
}
customElements.define('my-element', MyElement);
Now in HTML:
<my-element></my-element>
Component will render, but its styles won't conflict with external ones.
When to Use Shadow DOM?
Suitable for:
- Web Components (e.g.,
<my-button>,<user-card>) - UI libraries with own styles (without conflicts)
- Encapsulating logic and markup
Not required if:
- You work within frameworks (React, Vue) that solve isolation differently
- Components don't require strict isolation from external CSS
Conclusion:
Shadow DOM is way to create isolated, safe components with own styles and structure. It's foundation of Web Components and used to achieve encapsulation and UI reuse.