CSS - Pseudo-class :host



The CSS pseudo-class selector :host is mainly useful in styling the host element or the container of a web component, from within the component's shadow DOM. A web component is a custom element that is defined and built using HTML, JavaScript or CSS. These components are reusable.

When the pseudo-class :host is used to style, it targets the element that hosts the web component, unlike targeting the elements within the shadow DOM itself. This is helpful in encapsulation of styles within a web component and prevents their leakage to other elements or getting affected by the external styling.

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

Syntax

:host {
   /* ... */ 
}

CSS :host Example

Here is an example of :host pseudo-class, where a custom element has been defined using JavaScript and :host pseudo-class is used to style it:

<html>
<head>
<style>
   li {
      padding: 3px;
   }
   body {
      font-size: 1em;
      background-color: peachpuff;
   }

</style>
</head>
<body>
    <h1><sample-span>:host</sample-span> pseudo-class</h1>
    <ul>See the list:
    <li><sample-span>Web component - Custom element</sample-span></li>
    <li><sample-span>Host element</sample-span></li>
    <li><sample-span>HTML, JS, CSS</sample-span></li>
    </ul>
   <script>
   class SampleSpan extends HTMLElement {
    constructor() {
    super();

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

    const shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.appendChild(style);
    shadowRoot.appendChild(span);

    style.textContent = `
       :host { background-color: yellow; padding: 2px 5px; color: blue; }
       :host { border: 2px solid red;}
    `;
 }
 }

    // Define the new element
    customElements.define('sample-span', SampleSpan);
   </script>
</body>
</html>
Advertisements