liveBook · Manning

Shadow host

As explained in Vanilla Web

The element to which a shadow root is attached and which represents the component externally.

A shadow host is the element that owns an attached shadow root. It appears in the page DOM and forms the boundary between that DOM and the shadow tree. The host is not the shadow tree itself: it is the custom element through which the component is represented externally. section 7.5.1 section 7.5.2

The host remains a regular element in the page’s CSS cascade. Inside a shadow tree, the `:host` pseudo-class selects that element, allowing component styles to set its display behavior. Custom elements are inline by default unless that behavior is overridden. section 7.7 section 7.8.3

Listing 7.4 A web component using shadow DOM
<style>
button {
  background-color: black;
  color: white;
}
</style>

<script>
  class MyComponent extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' }); #1
    }
    connectedCallback() {
      this.shadowRoot.innerHTML = ` #2
        <style>
            h1 {
                border: 1px solid gray;
            }
        </style>
        <button>Click me</button>
      `;
    }
  }
  customElements.define('my-component', MyComponent);
</script>

<h1>CSS with components</h1>
<my-component></my-component>

See a custom element attach a shadow root and keep its internal styles separate from page styles. section 7.8.3

How Vanilla Web covers it

How deep it goes
Defines the host as a boundary and demonstrates `:host` styling, while deferring broader lifecycle details.
Examples
Uses a counter-button custom element and a shadow-DOM component with isolated styles.
What you can do after
Apply `:host` to style a shadow-DOM host, including setting its display behavior.
How it connects
Connects custom elements, shadow DOM, light DOM, component interfaces, and CSS encapsulation.

Also explained in

Compare how 3 books explain shadow host →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.