Styling

This documentation is a work in progress. It describes prerelease software, and is subject to change.

Style your element with CSS by including a style block in its template. These styles are encapsulated; they will only apply to your component.

Starting code

my-element.js

/**
 * Try LitElement https://lit-element.polymer-project.org/try
 * Starting code for 6. Style
 */

import { LitElement, html } from '@polymer/lit-element'; 

class MyElement extends LitElement {
  static get properties() {
    return {
      message: { type: String },
      myArray: { type: Array },
      myBool: { type: Boolean }
    };
  }
  
  constructor() {
    super();
    this.message='Hello world! From my-element';
    this.myArray = ['an','array','of','test','data'];
    this.myBool = true;
  }

  render() {
    return html`
      <!-- TODO: Add a style block. -->

      <!-- TODO: Add a styled paragraph. -->

      <p>${this.message}</p>
      <ul>
        ${this.myArray.map(item => html`<li>${item}</li>`)}
      </ul>
      ${this.myBool?
        html`<p>Render some HTML if myBool is true</p>`:
        html`<p>Render some other HTML if myBool is false</p>`}
      <button @click="${this.clickHandler}">Click</button>
    `;
  }

  clickHandler(event) {
    console.log(event.target);
    this.myBool = !this.myBool;
  }
}
customElements.define('my-element', MyElement);

  1. Define your styles.

    To define your styles, add the following code to your template:

    <style>
      p {
        font-family: Roboto;
        font-size: 16px;
        font-weight: 500;
      }
      .red {
        color: red;
      }
      .blue {
        color: blue;
      }
    </style>
    
  2. Apply your styles.

    Use myBool to apply the styles conditionally. Add the following paragraph to your template:

     <p class="${this.myBool?'red':'blue'}">styled paragraph</p>
    

If you’re stuck, click Launch Code Editor below to see the completed code for Step 6.

Congratulations - you’ve made your first element with LitElement. Next, see the Getting Started guide and set up LitElement locally.