Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Shadow DOM and Styling

Styling Lit Components

Style Lit components with the css tag and static styles: scoped rules, :host and :host-context, dynamic classes, style bindings, unsafeCSS and why inline styles still have a place.

Lit components render into a shadow root, so their styles are scoped. You write ordinary CSS, put it in a css tagged template, and Lit makes sure it applies only inside that component. This lesson covers the main ways to style: static styles, :host rules, class and style bindings, and a few special cases.

If shadow DOM is new to you, read Shadow DOM Basics first. The key point: your selectors cannot leak out, and page selectors cannot reach in.

static styles and the css tag

Declare styles on the class with static styles. The value is the result of the css tag, or an array of such results.

A styled button component

A few things to notice:

  • The selector button only matches the button inside this component. Every PillButton instance shares one parsed stylesheet, which is cheap.
  • :host styles the custom element itself (display, margins, size).
  • :host([tone="quiet"]) reacts to an attribute on the host. Setting reflect: true on the property keeps that attribute in sync when code changes tone, which is why the example declares it.

Why the css tag and not a plain string

The css tag creates a CSSResult, which Lit turns into a constructable stylesheet and adopts into the shadow root. A plain template string would not. The tag also blocks injection: it only accepts other css results or numbers in ${...}, not arbitrary strings, because untrusted text in a stylesheet could load files or hide content.

JavaScript
const gap = 8;
static styles = css`
  :host { display: grid; gap: ${gap}px; }     /* numbers are fine */
`;

If you really have a trusted string, such as a value from your own design-token file, wrap it with unsafeCSS:

JavaScript
import { unsafeCSS } from "lit";
const brand = "#2d5bd8";                      // from your own code, never from users
static styles = css`a { color: ${unsafeCSS(brand)}; }`;

:host in detail

The host is the outer box of your component, so a few :host rules are in almost every component:

CSS
:host { display: block; }                 /* default is inline */
:host([hidden]) { display: none; }        /* respect the hidden attribute */
:host([disabled]) { opacity: .5; pointer-events: none; }
:host(:focus-within) { outline: 2px solid #2d5bd8; }
:host-context(.dark) { color: white; }    /* a theme class on any ancestor */

Be careful with :host-context(): Firefox and Safari do not support it. Prefer custom properties for theming (see CSS Custom Properties and Parts).

The hidden rule is worth remembering. A rule :host { display: block } has higher priority than the browser's built-in [hidden] { display: none }, so a component with display: block ignores the hidden attribute until you add the :host([hidden]) line.

Dynamic classes: classMap

Often the style depends on state. The classMap directive turns an object into a class list and updates only what changed.

Toggle classes with classMap

classMap must be the only expression in the class attribute, so put static classes into the object (chip: true) rather than writing class="chip ${classMap(...)}". Built-in Directives covers the rest of the family.

Dynamic inline styles: styleMap

For values that change continuously (a progress width, a color from data) a CSS class per value is impractical. Use styleMap, or set a custom property that your stylesheet reads. Both avoid string concatenation:

JavaScript
import { styleMap } from "lit/directives/style-map.js";

render() {
  return html`<div class="bar" style=${styleMap({ width: this.percent + "%" })}></div>`;
}

Another good option is a custom property on the host: this.style.setProperty("--progress", this.percent), with width: calc(var(--progress) * 1%) in the stylesheet. That keeps layout logic in CSS.

Composing and ordering styles

static styles accepts an array. Later entries override earlier ones when specificity is equal.

JavaScript
static styles = [resetStyles, buttonStyles, css`.mine { color: red }`];

Subclasses can extend their parent's styles with super.styles:

JavaScript
class DangerButton extends PillButton {
  static styles = [super.styles, css`button { background: #c62828; }`];
}

Sharing and reusing styles across many components gets its own lesson: Shared and Adopted Stylesheets.

Light DOM styles and ::slotted

Children that the page author put inside your element belong to the page, not to the shadow root. Your styles cannot match them with ordinary selectors. The ::slotted() pseudo-element can style the top-level slotted nodes:

CSS
::slotted(h2) { margin-top: 0; color: #223; }
::slotted(*) { font-family: inherit; }   /* top-level only, not descendants */

::slotted has limits: it cannot select descendants of slotted elements, and the page's own styles beat it in a conflict.

Fallback when stylesheets are unavailable

Lit uses constructable stylesheets where supported (all current browsers) and falls back to inserting <style> tags otherwise. You do not write extra code for this.

Common mistakes

  • Writing styles in a plain string instead of the css tag. They will not be applied.
  • Putting a user-supplied string in a css tag with unsafeCSS. It is an injection risk.
  • Expecting your selectors to style slotted children. They belong to the page; use ::slotted() for top-level nodes.
  • Setting display: block on :host and then wondering why hidden stopped working.
  • Writing class="a ${classMap(...)}". Lit throws an error; classMap must be the entire attribute value.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you declare the CSS of a Lit component?

    static styles with the css tag is attached to the shadow root once and shared by all instances.
  2. 2. Which tag lets you insert a trusted string into a css template?

    css only accepts css results and numbers. unsafeCSS marks a trusted string as safe, so never use it with user input.
  3. 3. How do you style a component differently when it has the attribute tone="quiet"?

    :host(selector) matches the host when it also matches the selector.
  4. 4. What is the rule for classMap in a class attribute?

    classMap controls the whole class attribute, so static class names go inside its object.

Summary

  • Declare styles with static styles and the css tag; they are scoped and shared by every instance.
  • :host, :host([attr]) and :host(:hover) style the component's own outer box.
  • Use classMap for toggled classes and styleMap or custom properties for dynamic values.
  • static styles can be an array, and subclasses can extend with super.styles.
  • Use ::slotted() to style top-level slotted children; avoid :host-context for cross-browser theming.

Next: CSS Custom Properties and Parts