Search code examples
cssweb-componentlit-elementlit-htmllit

How to style dynamically in lit?


Good time How to style dynamically in lit? My main goal is to change the color of an element according to the user's input in the input element.

My code screen shoot


Solution

  • You can't use ‍${} in lit css tag function!

    But you can select element and then change style

    import {html, css, LitElement} from 'lit';
    import {customElement, property, query} from 'lit/decorators.js';
    
    @customElement('dynamic-style')
    export class DynamicStyle extends LitElement {
      static styles = css`
        label {
          color: #023047;
        }
      `;
    
      @property()
      color: string;
    
      @query('input') input: HTMLSelectElement | undefined;
      @query('label') label: HTMLSelectElement | undefined;
    
      render() {
        return html`
          <label for="color-input">HEX color: </label>
          <input id="color-input" placeholder="#023047" />
        `;
      }
    
      firstUpdated() {
        this.input.addEventListener('input', () => {
          this.label.style.color = this.input.value;
        });
      }
    }
    

    lit playground

    Also read: Dynamic classes and styles | Lit Doc

    Use CSS variable in Lit