You're viewing docs for an older version of Lit.
For the current version, visit lit.dev.

Styles

This page describes how to add styles to your component.

Your component’s template is rendered to its shadow DOM tree. The styles you add to your component are automatically scoped to the shadow tree, so they don’t leak out and affect other elements.

Add styles to your component

For optimal performance, define scoped styles in a static styles property.

Define styles in a tagged template literal, using the css tag function:

import { LitElement, css, html } from 'lit-element';

class MyElement extends LitElement {
  static get styles() {
    return css`
      div { color: red; }
    `;
  }
  render() { 
    return html`
      <div>I'm styled!</div> 
    `;
  }
}

The styles you add to your component are scoped using shadow DOM. For a quick overview of shadow DOM styling, see Shadow DOM styling overview.

The value of the static styles property can be:

The static styles property is usually the best way to add styles to your component, but there are some use cases you can’t handle this way—for example, linking to an external style sheet. For alternate ways to add styles, see Define scoped styles in the template.

Expressions in static styles

Static styles apply to all instances of a component. Any expressions in CSS are evaluated once, then reused for all instances.

To allow for theming or per-instance style customization, use CSS variables and custom properties to create configurable styles.

To prevent LitElement-based components from evaluating potentially malicious code, the css tag only allows nested expressions that are themselves css tagged strings or numbers.

import { LitElement, html, css } from 'lit-element';

const mainColor = css`red`;

class MyElement extends LitElement {
  static get styles() {
    return css`
      div { color: ${mainColor} }
    `;
  }
  render() {
    return html`<div>Some content in a div</div>`;
  }
}

customElements.define('my-element', MyElement);

Code Editor not supported on this browser

This restriction exists to protect applications from security vulnerabilities whereby malicious styles, or even malicious code, can be injected from untrusted sources such as URL parameters or database values.

If you must use an expression in a css literal that is not itself a css literal, and you are confident that the expression is from a fully trusted source such as a constant defined in your own code, then you can wrap the expression with the unsafeCSS function:

import { LitElement, html, css, unsafeCSS } from 'lit-element';

class MyElement extends LitElement {
  static get styles() {
    const mainColor = 'red';

    return css`
      div { color: ${unsafeCSS(mainColor)} }
    `;
  }
  render() {
    return html`<div>Some content in a div</div>`;
  }
}

customElements.define('my-element', MyElement);

Code Editor not supported on this browser

Only use the unsafeCSS tag with trusted input. Injecting unsanitized CSS is a security risk. For example, malicious CSS can “phone home” by adding an image URL that points to a third-party server.

Inheriting styles

Using an array of tagged template literals, a component can inherit the styles from a LitElement superclass, and add its own styles:

class MyElement extends SuperElement {
  static get styles() {
    return [
      super.styles,
      css`...`
    ];
  }
}
Code Editor not supported on this browser

Sharing styles

You can share styles between components by creating a module that exports tagged styles:

import { css } from 'lit-element';

export const buttonStyles = css`
  .blue-button {
    color: white;
    background-color: blue;
  }
  .blue-button:disabled {
    background-color: grey;
  }`;

Your element can then import the styles and add them to its static styles property:

import { buttonStyles } from './button-styles.js';

class MyElement extends LitElement {
  static get styles() {
    return [
      buttonStyles,
      css`
        :host { display: block;
          border: 1px solid black;
        }`
    ]
  }
  ...
}

You can also import an external style sheet by adding a <link> element to your template, but this has a number of limitations. For details, see Import an external stylesheet.

Shadow DOM styling overview

This section gives a brief overview of shadow DOM styling.

Styles you add to a component can affect:

Style the shadow tree

LitElement templates are rendered into a shadow tree by default. Styles scoped to an element’s shadow tree don’t affect the main document or other shadow trees. Similarly, with the exception of inherited CSS properties, document-level styles don’t affect the contents of a shadow tree.

When you use standard CSS selectors, they only match elements in your component’s shadow tree.

class MyElement extends LitElement {
  static get styles() {
    // Write styles in standard CSS
    return css`
      * { color: red; }
      p { font-family: sans-serif; }
      .myclass { margin: 100px; }
      #main { padding: 30px; }
      h1 { font-size: 4em; }
    `;
  }
  render() {
    return html`
      <p>Hello World</p>
      <p class="myclass">Hello World</p>
      <p id="main">Hello World</p>
      <h1>Hello World</h1>
    `;
  }
}
Code Editor not supported on this browser

Style the component itself

You can style the component itself using special :host selectors. (The element that owns, or “hosts” a shadow tree is called the host element.)

To create default styles for the host element, use the :host CSS pseudo-class and :host() CSS pseudo-class function.

static get styles() {
  return css`
    /* Selects the host element */
    :host { 
      display: block; 
    }

    /* Selects the host element if it is hidden */
    :host([hidden]) { 
      display: none; 
    }
  `;
}
Code Editor not supported on this browser

Note that the host element can be affected by styles from outside the shadow tree, as well, so you should consider the styles you set in :host and :host() rules as default styles that can be overridden by the user. For example:

my-element {
  display: inline-block;
}

Style the component’s children

Your component may accept children (like a <ul> element can have <li> children). To render children, your template needs to include one or more <slot> elements, as described in Render children with the slot element.

The <slot> element acts as a placeholder in a shadow tree where the host element’s children are displayed. For example:

class MyElement extends LitElement {
  render() {
    return html`<slot></slot>`;
  }
}
<my-element><p>Slotted content</p></my-element>
Code Editor not supported on this browser

Use the ::slotted() CSS pseudo-element to select children that are included in your template via <slot>s.

import { LitElement, html, css } from 'lit-element';

class MyElement extends LitElement {
  static get styles() {
    return css`
      ::slotted(*) { font-family: Roboto; }
      ::slotted(p) { color: blue; }
      div ::slotted(*) { color: red; }
    `;
  }
  render() {
    return html`
      <slot></slot>
      <div><slot name="hi"></slot></div>
    `;
  }
}
customElements.define('my-element', MyElement);

Code Editor not supported on this browser

Note that only direct slotted children can be styled with ::slotted().

<my-element>
  <div>Stylable with ::slotted()</div>
</my-element>

<my-element>
  <div><p>Not stylable with ::slotted()</p></div>
</my-element>

Also, children can be styled from outside the shadow tree, so you should regard your ::slotted() styles as default styles that can be overridden.

my-element div {
  // Outside style targetting a slotted child can override ::slotted() styles
}

Watch out for limitations in the Shady CSS polyfill around slotted content! See the Shady CSS limitations for details on how to use the ::slotted() syntax in a polyfill-friendly way.

Configurable styles with custom properties

Static styles are evaluated once per class. Use CSS variables and custom properties to make styles that can be configured at runtime:

static get styles() {
  return css`
    :host { color: var(--themeColor); }
  `;
} 
<style>
  html { 
    --themeColor: #123456;
  }
</style>
<my-element></my-element>

See the section on CSS custom properties for more information.

Define scoped styles in the template

We recommend using static styles for optimal performance. However, sometimes you may want to define styles in the LitElement template. There are two ways to add scoped styles in the template:

Each of these techniques has its own set of advantages and drawbacks.

In a style element

We recommend using static styles for optimal performance. However, static styles are evaluated once per class. Sometimes, you might need to evaluate styles per instance.

We recommend using CSS properties to create customizable styles. However, you can also include <style> elements in a LitElement template. These are updated per instance.

render() {
  return html`
    <style>
      /* updated per instance */
    </style>
    <div>template content</div>
  `;
}

Expressions and style elements

The most intuitive way to evaluate per-instance styles has some important limitations and performance issues. We consider the example below to be an anti-pattern:

// Anti-pattern!
render() {
  return html`
    <style>
      :host {
        /* Warning: this approach has limitations & performance issues! */
        color: ${myColor}
      } 
    </style>
    <div>template content</div>
  `;
}

Expressions inside a <style> element won’t update per instance in ShadyCSS, due to limitations of the ShadyCSS polyfill. See the ShadyCSS readme for more information.

Additionally, evaluating an expression inside a <style> element is inefficient. When any text inside a <style> element changes, the browser must re-parse the whole <style> element, resulting in unnecessary work.

If you need to evaluate expressions inside a <style> element, use the following strategy to avoid creating performance problems:

Example

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

const perClassStyle = html`
  <style>
    :host {
      display: block;
      font-family: Roboto;
      font-size: 14px; 
    }
  </style>
`;

const blueText = html`
  <style> :host { color: blue; } </style>
`;

const redText = html`
  <style> :host { color: red; } </style>
`;

class MyElement extends LitElement {
  constructor() {
    super();
    this.perInstanceStyle = redText;
  }
  render() {
    return html`
      ${perClassStyle}
      ${this.perInstanceStyle}
      <div>Hello World</div>
    `;
  }
}

customElements.define('my-element', MyElement);

Code Editor not supported on this browser

Import an external stylesheet

We recommend placing your styles in a static styles property for optimal performance. However, you can include an external style sheet in your template with a <link>:

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

class MyElement extends LitElement {
  render() {
    return html`
      <link rel="stylesheet" href="./app-styles.css">
      <button>a button</button>
      <div>a div</div>
    `;
  }
}

customElements.define('my-element', MyElement);

Code Editor not supported on this browser

There are some important caveats though:

Dynamic classes and styles

One way to make styles dynamic is to add bindings to the class or style attributes in your template.

The lit-html library offers two directives, classMap and styleMap, to conveniently apply classes and styles in HTML templates.

For more information on these and other lit-html directives, see the documentation on lit-html built-in directives.

To use styleMap and/or classMap:

  1. Import classMap and/or styleMap:

    import { classMap } from 'lit-html/directives/class-map';
    import { styleMap } from 'lit-html/directives/style-map';
    
  2. Use classMap and/or styleMap in your element template:

    constructor() {
      super();
      this.classes = { mydiv: true, someclass: true };
      this.styles = { color: 'green', fontFamily: 'Roboto' };
    }
    render() {
      return html`
        <div class=${classMap(this.classes)} style=${styleMap(this.styles)}>
          Some content
        </div>
      `;
    }
    
Code Editor not supported on this browser

classMap syntax

classMap applies a set of classes to an HTML element:

<div class=${classMap({alert:true,info:true})}>Content.</div>
<!-- Equivalent: <div class="alert info">Content.</div> -->
Code Editor not supported on this browser

styleMap syntax

styleMap applies a set of CSS rules to an HTML element:

<button style=${styleMap({
  backgroundColor: 'blue',
  border: '1px solid black'
})}>A button</button>

<!-- Equivalent: 
  <button style="
    background-color:blue;
    border: 1px solid black;
  ">A button</button>
-->
Code Editor not supported on this browser

To refer to hyphenated properties such as font-family, use the camelCase equivalent (fontFamily) or place the hyphenated property name in quotes ('font-family').

To refer to custom CSS properties such as --custom-color, place the whole property name in quotes ('--custom-color').

Inline style or CSS styleMap equivalent
background-color: blue;
backgroundColor: 'blue'

or

'background-color': 'blue'
font-family: Roboto, Arial, sans-serif;
fontFamily: 'Roboto, Arial, sans-serif'

or

'font-family': 'Roboto, Arial, sans-serif'
--custom-color: #FFFABC; '--custom-color': '#FFFABC;'
--otherCustomColor: #FFFABC; '--otherCustomColor': '#FFFABC;'
color: var(--customprop, blue); color: 'var(--customprop, blue)'

Examples

Inline style syntax:

<div style="
  background-color:blue;
  font-family:Roboto;
  --custom-color:#e26dd2;
  --otherCustomColor:#77e26d;">
</div>

Equivalent CSS syntax:

div {
  background-color: blue;
  font-family: Roboto;
  --custom-color: #e26dd2;
  --otherCustomColor: #77e26d;
}

Equivalent styleMap syntax:

html`
  <div style=${styleMap({
    'background-color': 'blue',
    fontFamily: 'Roboto',
    '--custom-color': '#e26dd2',
    '--otherCustomColor': '#77e26d'
  })}></div>
`
Code Editor not supported on this browser

Theming

CSS inheritance

CSS inheritance lets parent and host elements propagate certain CSS properties to their descendents.

Not all CSS properties inherit. Inherited CSS properties include:

See CSS Inheritance on MDN for more information.

You can use CSS inheritance to set styles on an ancestor element that are inherited by its descendents:

<style>
html { 
  font-family: Roboto;
}
</style>
<div>
  <p>Uses Roboto</p>
</div>

Similarly, host elements pass down inheritable CSS properties to their shadow trees.

You can use the host element’s type selector to style it:

<style>
  my-element { font-family: Roboto; }
</style>
<my-element></my-element>
class MyElement extends LitElement {
  render() { 
    return html`<p>Uses Roboto</p>`; 
  }
}
Code Editor not supported on this browser

You can also use the :host CSS pseudo-class to style the host from inside its own template:

static get styles() {
  return css`
    :host {
      font-family: Roboto;
    }
  `;
}
render() {
  return html`
    <p>Uses Roboto</p>
  `;
}
Code Editor not supported on this browser

Type selectors have higher specificity than :host.

An element type selector has higher specificity than the :host pseudo-class selector. Styles set for a custom element tag will override styles set with :host and :host():

<style>
  my-element { font-family: Courier; }
</style>
<my-element></my-element>
class MyElement extends LitElement {
  static get styles() { 
    return css`:host { font-family: Roboto; }`
  }
  render() {
    return html`<p>Will use courier</p>`;
  }
}
Code Editor not supported on this browser

CSS custom properties

All CSS custom properties (--custom-property-name) inherit. You can use this to make your component’s styles configurable from outside.

The following component sets its background color to a CSS variable. The CSS variable uses the value of --my-background if it’s available, and otherwise defaults to yellow:

class MyElement extends LitElement {
  static get styles() { 
    return css`
      :host { 
        background-color: var(--my-background, yellow); 
      }
    `;
  }
  render() {
    return html`<p>Hello world</p>`;
  }
}

Users of this component can set the value of --my-background, using the my-element tag as a CSS selector:

<style>
  my-element {
    --my-background: rgb(67, 156, 144);
  }
</style>
<my-element></my-element>

--my-background is configurable per instance of my-element:

<style>
  my-element {
    --my-background: rgb(67, 156, 144);
  }
  my-element.stuff {
    --my-background: #111111;
  }
</style>
<my-element></my-element>
<my-element class="stuff"></my-element>

If a component user has an existing app theme, they can easily set the host’s configurable properties to use theme properties:

<html>
  <head>
    <title>lit-element code sample</title>
    <script type="module" src="./my-element.js"></script>
    <style>
      html { --themeColor1: rgb(67, 156, 144); }
      my-element {
        --myBackground: var(--themeColor1);
        --myColor: rgb(156, 67, 152);
      }
    </style>
  </head>
  <body>
    <my-element></my-element>
  </body>
</html>

Code Editor not supported on this browser

See CSS Custom Properties on MDN for more information.

A simple example theme

index.html

<html>
  <head>
    <script type="module" src="./my-element.js"></script>
    <title>lit-element code sample</title>
    <style>
      html {
        --theme-primary: green;
        --theme-secondary: aliceblue;
        --theme-warning: red;
        --theme-font-family: Roboto;
      }
      my-element { 
        --my-element-text-color: var(--theme-primary); 
        --my-element-background-color: var(--theme-secondary); 
        --my-element-font-family: var(--theme-font-family);
      } 
      .warning {
        --my-element-text-color: var(--theme-warning); 
      }
    </style>
  </head>
  <body>
    <my-element></my-element>
    <my-element class="warning"></my-element>
  </body>
</html>

my-element.js

import { LitElement, html, css } from 'lit-element';

class MyElement extends LitElement {
  static get styles() { 
    return css`
      :host { 
        display: block;
        color: var(--my-element-text-color, black); 
        background: var(--my-element-background-color, white);  
        font-family: var(--my-element-font-family, Roboto);
      }
      :host([hidden]) {
        display: none;
      }
    `;
  }
  render() {
    return html`<div>Hello World</div>`;
  }
}
customElements.define('my-element', MyElement);

Code Editor not supported on this browser