Search code examples
polymerweb-componentlit-element

How can I add a class based on a property in lit-element?


How can I add a conditional class using web component property? So lets say I have an image component which gets the property fullscreen then I want to add the class fullscreen to my component (using lit element);

What I have now (not working)

export class Image extends LitElement{
static get styles() {
    return css `
  :host {
    display: block;
    height: 100%;
  }

  picture {
      display: block;
  }

  .fullscreen img {
      position: absolute;
      object-fit: cover;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      height: 100%;
      width: 100%;
      z-index: -2;
  }
`;
}

static get properties() {
    return {
        fullScreen: {
            type: Boolean
        },
        imageSrc: {
            type: String
        }
    };
}

constructor() {
    super();
    this.fullScreenClass = {
        fullscreen: this.fullScreen
    }
    this.imageSrc = "";
}

render() {
    return html `
    <picture class=${classMap(this.fullScreenClass)}>
    <source
    srcset="${this.imageSrc}">
  <img scr="${this.imageSrc}">
    </picture>
`;
}

}

How I want to use it

<test-image fullscreen
  imageSrc="https://www.driving.co.uk/s3/st-driving-prod/uploads/2019/05/Aston-Martin-Rapide-E-Charging-01.jpg">
</test-image>

Solution

  • You can use attribute css selectors

    :host([fullscreen]) {
        // your styling for fullscreen
      }
    

    This style will get applied to below component instance in HTML bacause of fullscreen attribute

    <test-image fullscreen
      imageSrc="https://www.driving.co.uk/s3/st-driving-prod/uploads/2019/05/Aston-Martin-Rapide-E-Charging-01.jpg">
    </test-image>