Sub topic 3
Shadow DOM: encapsulating markup and styles
This chapter assumes you know basic HTML and CSS, JavaScript classes, and how the browser DOM and event listeners work. It also assumes you have seen the custom element example from the previous chapter. Here you will learn what a shadow root is, how it isolates markup and styles, and where the isolation has gaps.
The problem shadow DOM solves
In a normal page, every element lives in one shared tree. A CSS rule like p { color: red; } reaches every paragraph, including paragraphs inside a widget you imported. Calling document.querySelector('input') can return an input that belongs to someone else's component. Two components can also reuse the same id and collide.
Shadow DOM is a browser standard that gives an element its own private subtree. Markup, styles, and queries inside that subtree are separated from the rest of the page. The element that owns the private subtree is called the host. The private subtree is called the shadow tree, and its top node is the shadow root.
Creating a shadow root
You attach a shadow root with attachShadow(). This is the same call used in the custom element example:
class NoteCard extends HTMLElement {
connectedCallback() {
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = `
<style>p { color: crimson; }</style>
<p>Private paragraph</p>
`;
}
}
customElements.define('note-card', NoteCard);The <style> rule above applies only to paragraphs inside this shadow tree. A <p> elsewhere on the page stays unchanged. A page-level rule such as p { font-size: 2rem; } also does not reach the paragraph inside the shadow tree.
The mode option controls whether outside code can reach in:
| Mode | `element.shadowRoot` returns | Typical use |
|---|---|---|
| `open` | The shadow root | Most components; allows debugging and testing tools |
| `closed` | `null` | Rare; hides the root from casual access |
A closed root is not a security boundary. The class that created it still holds a reference, and other code can sometimes intercept attachShadow before the component runs. Treat it as a hint, not protection.
A host can have only one shadow root. Calling attachShadow() a second time on the same element throws an error. Only some elements can host a shadow root. Custom elements and a fixed list of built-in elements such as div, section, and article qualify. Elements like input and a do not.
What gets isolated
Three things are separated by the shadow boundary.
- Markup queries.
document.querySelector('p')does not return elements inside a shadow tree. To reach them you must start from the shadow root, for examplehost.shadowRoot.querySelector('p'). - CSS. Selectors in the outer document do not match elements inside the shadow tree, and selectors inside the shadow tree do not match the outside.
- Identifiers. An
idinside one shadow tree does not conflict with the sameidin another tree or in the document.
The diagram shows the structure.
Inheritance still crosses the boundary
Encapsulation does not block every style. CSS properties that inherit by default, such as color, font-family, font-size, and line-height, still flow from the host into the shadow tree. If the page sets body { font-family: Georgia; }, text inside the shadow tree uses Georgia unless the component overrides it.
Non-inherited properties such as margin, border, and background do not cross. This is why a component usually looks consistent with its surroundings in text styling but is not disturbed by layout rules aimed at the page.
Custom properties, also called CSS variables, inherit too. That makes them the standard way to let a page style a component on purpose:
<style>
note-card { --note-accent: teal; }
</style>
<note-card></note-card>
<script>
class NoteCard extends HTMLElement {
connectedCallback() {
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = `
<style>p { color: var(--note-accent, crimson); }</style>
<p>Styled through a custom property</p>
`;
}
}
customElements.define('note-card', NoteCard);
</script>The component reads --note-accent and falls back to crimson when the page does not set it. The component author decides which variables are part of its public styling surface.
Styling the host from inside
Inside a shadow tree, the :host selector matches the host element. You use it to set defaults for the element itself, such as its display value. Custom elements default to display: inline, so most components set it:
class NoteCard extends HTMLElement {
connectedCallback() {
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = `
<style>
:host { display: block; border: 1px solid #ccc; padding: 0.5rem; }
:host([highlight]) { background: lightyellow; }
</style>
<slot></slot>
`;
}
}
customElements.define('note-card', NoteCard);:host([highlight]) matches only when the host has a highlight attribute. Rules written in the outer document for note-card have higher priority than :host rules, so a page can still override these defaults.
Events and the shadow boundary
Events dispatched inside a shadow tree travel up to the document only if they are created with bubbles: true and composed: true. Without composed: true, the event stops at the shadow root.
Most built-in UI events, such as click, are composed. When such an event crosses the boundary, the browser retargets it. A listener outside the shadow tree sees event.target as the host element, not the inner element that was clicked. This hides the component's internal structure. Code that needs the real path can call event.composedPath(), which works for open roots.
Slots cross the boundary on purpose
The <slot> element, shown in the example above, marks where content supplied by the page appears inside the shadow tree. That content stays in the outer document. It is only displayed at the slot position. As a result, outer-page CSS still styles slotted content, and ::slotted(p) inside the shadow tree can apply limited styles to it. The next chapter on templates and slots covers this in detail.
Common errors
- Querying from the wrong place.
document.querySelectorreturnsnullfor elements inside a shadow tree. Start fromhost.shadowRoot. - Expecting global CSS to apply. A utility class defined on the page does not style elements inside a shadow tree. Pass values with custom properties or put the styles in the component.
- Attaching twice. A second
attachShadow()call on the same host throws. In a custom element, attach once, usually in the constructor. - Forgetting
composed: true. A custom event fired from inside a shadow tree never reaches outer listeners if it is not composed. - Leaving
displayat the default. An inline host ignores width and height. Set:host { display: block; }.
How this relates to Lightning Web Components
Lightning Web Components rely on this standard. Each LWC component is a custom element whose template renders into a shadow root. The framework attaches the root for you, so you do not call attachShadow() yourself. CSS in a component's stylesheet applies only to that component's template, which is the same isolation you saw here. Later chapters cover how LWC handles this in practice, including its synthetic shadow option for older browsers, which emulates shadow DOM behavior in JavaScript.
Exercise
A page contains <note-card> whose shadow root holds a <p>. The page stylesheet has p { color: blue; } and note-card { font-family: Georgia; }. The component's own shadow style sets no font and no color. What color and font does the inner <p> use, and why? How would you let the page change the paragraph color without editing the component?
Show answer
The paragraph does not turn blue, because the page's p selector cannot match elements inside the shadow tree. It uses Georgia, because font-family is an inherited property and inherited values cross the shadow boundary from the host. To let the page change the color, have the component use a custom property, for example p { color: var(--note-color, black); }, and let the page set note-card { --note-color: blue; }.