Search code examples
javascripthtmlcssweb-componentshadow-dom

Webcomponents :host:hover


Is there a way to add a css :hover effect on webcompoenents (not from the parent).

I have following example code

window.customElements.define('a-b', class extends HTMLElement {
  constructor() {
      super();
      this.attachShadow({mode: 'open'}).innerHTML = `
        <style>
          :host {
            display: block;
            height: 100px;
            width: 100px;
            background: red;
          }
          :host:hover {
            background: blue;
          }
          :host::selection {
            background: rgba(0, 0, 0, 0.15);
          }
        </style>
        <slot></slot>
      `;
  }
}

The :host::selection property works as expected. But the :host:hover does not seem to have any effect.

I know there are workarounds to this problem like:

  • wrapping everything inside a div
  • applying the :hover effect at the parent stylesheet

But I wanted to know if I am just missing something (since this does not seem too complex) for the sake of cleaner code.


Solution

  • For the sake of cleaner code, use instead the :host() syntax since :hover is a pseudo-class applied to the Custom Element. It is then selectable with:

    :host(:hover) { ... }
    

    Example:

    window.customElements.define('a-b', class extends HTMLElement {
      constructor() {
        super()
        this.attachShadow({mode: 'open'})
            .innerHTML = `
               <style>
                  :host(:hover) {
                    color: white;
                    background-color: blue;
                  }							
              </style>
              <slot></slot>`
      }
    })
    <a-b>Hello World</a-b>