Styling
Style your component with CSS by defining a static styles
getter in your class.
Starting code
my-element.js
// TODO: Import the css helper function
import { LitElement, html } from 'lit-element';
class MyElement extends LitElement {
static get properties() {
return {
message: { type: String },
myBool: { type: Boolean },
myArray: { type: Array }
};
}
// TODO: Add a static styles getter
constructor() {
super();
this.message = 'Hello world! From my-element';
this.myArray = ['an','array','of','test','data'];
this.myBool = true;
}
render() {
return html`
<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>
<!-- TODO: Add a styled paragraph -->
`;
}
clickHandler(event) {
console.log(event.target);
this.myBool = !this.myBool;
}
}
customElements.define('my-element', MyElement);
Code Editor not supported on this browser
-
Import the
css
helper function.In my-element.js, replace the
import
statement with the following code:import { LitElement, html, css } from 'lit-element';
-
Define your styles.
To define your styles, add a static
styles
getter to your class:static get styles() { return css` p { font-family: Roboto; font-size: 16px; font-weight: 500; } .red { color: red; } .blue { color: blue; } `; }
-
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>
Here’s the completed code for this step:
my-element.js
import { LitElement, html, css } from 'lit-element';
class MyElement extends LitElement {
static get properties() {
return {
message: { type: String },
myArray: { type: Array },
myBool: { type: Boolean }
};
}
static get styles() {
return css`
p {
font-family: Roboto;
font-size: 16px;
font-weight: 500;
}
.red {
color: red;
}
.blue {
color: blue;
}
`;
}
constructor() {
super();
this.message = 'Hello world! From my-element';
this.myArray = ['an','array','of','test','data'];
this.myBool = true;
}
render() {
return html`
<p class="${this.myBool?'red':'blue'}">styled paragraph</p>
<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);
Congratulations - you’ve made your first element with LitElement. Next, see the Getting Started guide and set up LitElement locally.