Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Shadow DOM and Styling

Shadow DOM Basics

Learn what shadow DOM is, how attachShadow creates a private tree, what open and closed modes mean, how style scoping works and how Lit creates the shadow root for you.

Normal HTML has one global scope. A CSS rule p { color: red } in one corner of the page affects every paragraph everywhere, and document.querySelector can reach any element. That is convenient for a small page and painful for components, because the styles and structure of one component leak into others.

Shadow DOM gives an element its own private DOM tree and its own style scope. CSS from outside does not reach in, CSS from inside does not leak out, and querySelector on the page does not see the internal elements. It is the feature that makes a component a black box you can drop into any page.

Attaching a shadow root

Call attachShadow on an element to create a shadow root. Then fill it like any other node. The element that owns the shadow root is called the host.

Style isolation

The page rule colors the first paragraph red but never reaches the one inside the shadow root. The component's own p rule stays inside too, so it cannot disturb the page. Neither side needs to know what the other uses, which means no naming conventions such as BEM prefixes are needed to avoid clashes.

flowchart TD
  H["shadow-demo element (host)"] --> S["#shadow-root"]
  S --> ST["style"]
  S --> P["p"]
  H -. "light DOM children<br/>(optional, shown via slot)" .-> L["slotted content"]

The host element owns a shadow tree that is separate from the page tree.

Open and closed

attachShadow needs a mode:

  • { mode: "open" } exposes the root as element.shadowRoot. Code and tools such as the browser inspector can look inside. This is the standard choice.
  • { mode: "closed" } returns the root only to the caller. element.shadowRoot is null.

Closed mode is not security. It only hides the root from casual code, and a determined script can still find ways in (for example by patching attachShadow before your component loads). It also makes testing and debugging harder. Use open, and Lit does too.

What does the outside see?

The last two lines show scoping: a page-level querySelector("b") finds nothing, because both <b> elements are inside shadow trees. You must ask the shadow root directly.

What is encapsulated

Thing Inside the shadow tree Behavior
CSS selectors Page styles do not match inside; inner styles do not match outside Scoped
querySelector Page queries do not find shadow elements Scoped
id values The same id may exist inside several shadow roots Scoped
Events Most events bubble out, with the target changed to the host (see Shadow DOM Events and Focus) Retargeted
Inherited CSS color, font-family, line-height and custom properties still inherit in Passes through

The last row matters. Shadow DOM blocks selectors, not inheritance. If the page sets body { font-family: Georgia }, text inside a shadow root inherits that font unless the component sets its own. This is how theming works: a component can use color: var(--card-text, black) and the page sets --card-text on an ancestor. See CSS Custom Properties and Parts.

The host element and :host

The host lives in the page's tree, so page CSS can style it from outside: shadow-demo { display: block }. Inside, the component styles its own host with the :host selector:

CSS
:host { display: block; padding: 12px; }
:host([compact]) { padding: 4px; }
:host(:hover) { background: #f5f5f5; }

Host styles from the page win over :host rules, so the page always has the final say about layout of the host. That is a good default: the author of the page can override the component's outer box.

Light DOM and shadow DOM together

Children that the page author writes inside the host stay in the light DOM. They are not shown automatically, because the shadow tree replaces the host's visual content. To show them, the shadow tree contains a <slot> element, and the browser projects the light children into it.

A slot shows light DOM children

The <strong> text and the sentence belong to the page, so page CSS can still style them. The border, label and background come from inside. Slots and Component Composition in Lit goes deeper.

Which elements can host a shadow root?

Custom elements, and a fixed list of built-ins: article, aside, blockquote, body, div, footer, h1 to h6, header, main, nav, p, section and span. Elements such as input, img or a cannot, because they already have their own internal behavior (some browsers implement them with a hidden user agent shadow tree).

Declarative shadow DOM

A shadow root can also be written in HTML with <template shadowrootmode="open">. The browser builds the shadow tree while parsing, without JavaScript. This is how server-side rendering of web components works, so users see content before scripts load. Lit supports it through @lit-labs/ssr, which is outside the scope of this track, but good to know about.

HTML
<info-card>
  <template shadowrootmode="open">
    <style>p { color: teal }</style>
    <p>Rendered by the parser.</p>
  </template>
</info-card>

Lit creates the shadow root for you

In a Lit component, you never call attachShadow. LitElement creates an open shadow root in createRenderRoot() and renders your render() result into it. Styles from static styles are attached to the root once and shared between all instances.

JavaScript
class InfoCard extends LitElement {
  static styles = css`:host { display: block; }`;
  render() { return html`<slot></slot>`; }
}

If you ever need a component without encapsulation (to let global CSS such as a utility framework reach in), override createRenderRoot() { return this; }. You give up style scoping and slots, so it is a last resort.

Common mistakes

  • Expecting a global stylesheet to style elements inside a component. It will not; share styles explicitly (see Shared and Adopted Stylesheets).
  • Using document.getElementById to find an element inside a component. Use this.shadowRoot.getElementById or renderRoot.querySelector.
  • Choosing closed mode "for security". It makes tests and tools harder and gives no real protection.
  • Forgetting that :host is display: inline by default, so layout properties such as width do nothing until you set display.
  • Calling attachShadow twice on one element. The second call throws.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a shadow root provide?

    Shadow DOM encapsulates structure and styles: outside selectors do not reach in, and inside styles do not leak out.
  2. 2. What is element.shadowRoot for an element with a closed shadow root?

    Closed mode returns the root only from attachShadow, so the property is null.
  3. 3. Which CSS still reaches inside a shadow root from the page?

    Selectors do not cross the boundary, but inheritance and custom properties do.
  4. 4. Which selector styles the host element from inside the shadow tree?

    :host matches the element that owns the shadow root, and :host(selector) adds a condition.

Summary

  • attachShadow({ mode: "open" }) creates a private tree and style scope for the host element.
  • Selectors, ids and querySelector are scoped; inheritance and custom properties still pass through.
  • Use :host to style the host; the page can still override it.
  • Light DOM children appear through <slot>.
  • LitElement creates an open shadow root automatically and attaches static styles to it.

Next: Styling Lit Components