Search code examples
cssweb-componentshadow-domlit-element

CSS property 'cursor' not working with :host selector


I'm trying to figure out how to apply the property cursor when using :host selector.

Others properties are correctly applied, but not cursor.

:host([disabled]) {
    color: #626878;
    background-color: #C0C4CB;  
    cursor: not-allowed!important;  
}

:host refer to a web component made with LitElement.

Thanks for your help


Solution

  • Runs fine:

      customElements.define("my-element", class extends HTMLElement {
        connectedCallback() { // so attributes can be queried
          this
            .attachShadow({mode:"open"})
            .innerHTML = `<style>
                             :host {
                               display:    inline-block;
                             }
                             :host([disabled]) {
                               cursor:     not-allowed !important;
                               background: pink        !important;
                               color:      grey        !important;
                             }
                         </style>
                         <h1>&lt;my-element 
                             ${this.hasAttribute("disabled")?"disabled":""}></h1>`;
        }
      })
    <style>
      my-element{
        cursor:     pointer;
        background: lightgreen;
        color:      green;
      }
    </style>
    
    <my-element></my-element>
    <my-element disabled></my-element>

    Requires !important

    From https://web.dev/shadowdom-v1/

    One gotcha with :host is that rules in the parent page have higher specificity than :host rules defined in the element. That is, outside styles win. This allows users to override your top-level styling from the outside. Also, :host only works in the context of a shadow root, so you can't use it outside of shadow DOM.