CSS pseudo-class - :host()



The :host() CSS pseudo-class function allows you to select a custom element from inside its shadow DOM, but only if the selector (e.g. a class selector) given as the function's parameter matches the shadow host.

The :host() pseudo-class function has no effect when used outside a shadow DOM.

Syntax

:host(<compound-selector>) {
   /* ... */
}

Selects the shadow host, but only if it matches the selector argument.

:host(.special-custom-element) {
   /* ... */
}

CSS :host-function Example

The following example demonstrates how to use :host() pseudo-class function to select the shadow host of the custom element. The custom element in this case is a context-span element −

<html>
<head>
<style>
   div {
      font-size: 25px;
   }
</style>
</head>
<body>
   <div>
      <p>Tutorialspoint CSS - <a href="#"><context-span class="custom-host">:host()</context-span></a></p>
   </div>
   <script>
      class HostStyle extends HTMLElement {
         constructor() {
            super();
            const shadowRoot = this.attachShadow({ mode: 'open' });
            const styleElement = document.createElement('style');
            styleElement.textContent = `
               :host(.custom-host) {
                  color: blue;
                  background: pink;
               }`;/*applies the styling to custom element if it matches the class selector .custom-host*/
            shadowRoot.appendChild(styleElement);

            const spanElement = document.createElement('span');
            spanElement.textContent = this.textContent;

            shadowRoot.appendChild(spanElement);
         }
      }
      customElements.define('context-span', HostStyle);
   </script>
</body>
</html>
Advertisements