completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Styles in Lit

Learn Lit static styles with live examples: the css tag and its one shared sheet, unsafeCSS, sharing and inheriting styles, classMap, and light DOM.

By the end, you can
  • 01
    Style a Lit component the fast wayPut CSS in static styles with the css tag, and know why 100 instances share one stylesheet.
  • 02
    Share styles safelyShare a css module between components, keep a parent's styles in a subclass, and keep typed text out of unsafeCSS.
  • 03
    Style one instance, or skip shadow DOMUse custom properties, :host() attributes, classMap, and styleMap. Set shadowRootOptions, and know what createRenderRoot() returning this takes away.

How do you add styles to a Lit component?

Asha's online menu for Leaf and Kettle has grown. It lists 100 teas now, and each one is a tea-menu-item with its own shadow root. Ravi looks at the page and frowns. "Does every item carry its own copy of the CSS?"

How do you give a Lit component its styles? And how many copies of them does the browser keep?

In Lit, you style a component with static styles and the css tag. Lit makes one stylesheet from that CSS, for the whole class. Every instance's shadow root adopts the same sheet, so 100 menu items share one.

Here is the menu, with all 100 items:

100 menu items and the sheets they adoptPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="menu"></div><script type="module">  import { TeaMenuItem } from "./tea-menu-item.js";  const menu = document.querySelector("#menu");  for (let n = 1; n <= 100; n++) {    const item = document.createElement("tea-menu-item");    item.name = `Tea ${n}`;    menu.append(item);  }  const items = [...menu.children];  await Promise.all(items.map((item) => item.updateComplete));  const sheets = new Set(items.flatMap((item) => item.shadowRoot.adoptedStyleSheets));  console.log(`Items: ${items.length}. Sheet objects: ${sheets.size}`);  console.log(`It is TeaMenuItem.styles.styleSheet: ${sheets.has(TeaMenuItem.styles.styleSheet)}`);</script>
ResultLoading…
  • Lines 1 to 3 are the import map from lesson 20.1. The name lit means Lit 3.3.3, from esm.sh.
  • Line 6 loads the tea-menu-item.js tab. Lines 8 to 12 add 100 items, named Tea 1 to Tea 100.
  • Line 14 waits until every item has drawn.
  • Line 15 collects the adopted sheets of all 100 shadow roots in a Set, which keeps one of each object.
  • Line 16 prints how many there are. Line 17 checks that the one sheet is the class's own.

The tea-menu-item.js tab holds the component:

tea-menu-item.js: CSS in static stylesJavaScript
import { LitElement, html, css } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {} };

  static styles = css`
    :host { display: block; border-bottom: 1px solid seagreen; }
    h3 { margin: 4px 0; font: bold 16px Georgia, serif; }
  `;

  render() {
    return html`<h3>${this.name}</h3>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Line 1 takes css from Lit, next to LitElement and html.
  • Lines 6 to 9 are static styles. It's a static field: it belongs to the class, not to each item (static fields). It holds what the css tag returns.
  • Line 7 styles the host, and line 8 styles the name.
  • Line 12 draws the name. The template has no style element and no class names.

The menu shows 100 names, each with a green line under it. The console prints Items: 100. Sheet objects: 1 and It is TeaMenuItem.styles.styleSheet: true.

A card TeaMenuItem.styles, labeled one css result, with an arrow to a card CSSStyleSheet, labeled one sheet, made once. Four arrows go from that sheet to four cards: item 1 root, item 2 root, item 3 root, and item 100 root, labeled 100 shadow roots.TeaMenuItem.stylesone css resultCSSStyleSheetone sheet, made onceitem 1 rootitem 2 rootitem 3 rootitem 100 root100 shadow roots
Lit makes the sheet once, for the class. Every item's shadow root adopts the same object, so the page prints Sheet objects: 1. Four of the 100 roots are drawn.
Real-life analogyOne menu board on the wall

Leaf and Kettle has one menu board on the wall. Every table reads the same board. Asha paints it once, however many tables are full. She never prints a copy of the menu for each table.

In real life: The menu board on the wall
In JavaScript: One CSSStyleSheet for the class
In real life: Each table reading the board
In JavaScript: Each shadow root adopting that sheet
In real life: Painting the board once
In JavaScript: Lit making the sheet the first time it's needed
In real life: A printed copy on every table
In JavaScript: A style element inside every item
The main idea

static styles holds a component's CSS, written with the css tag. Lit makes one CSSStyleSheet from it for the class, and adopts that sheet into every instance's shadow root. Write each style once, and every instance shares it.

None of this is new to the browser. Lesson 11.5 shared one sheet between shadow roots by hand. Lesson 19.1 built the same idea into TeaElement. Lit does it for you. Why it matters: the browser parses a shared sheet once, however many items use it (MDN).

What does Lit's css tag do?

The css tag is a tag function: a function that runs on a template literal. It gets the literal's fixed strings and its values (tagged templates). Lit's css doesn't return a sheet. It returns a CSSResult: a small object that holds the CSS text and makes the sheet later.

Here is the whole trip, from the class to the shadow root:

  1. When the class is made, css joins its strings into one text, cssText (css-tag.ts, lines 143 to 159).
  2. When you define the element, the browser reads observedAttributes. Lit's getter for it runs finalize() once for the class (reactive-element.ts, lines 659 to 669). It turns static styles into a list, elementStyles (line 899).
  3. Each new element calls createRenderRoot(). It attaches a shadow root and calls adoptStyles() with that list (lines 1119 to 1130).
  4. adoptStyles() sets the root's adoptedStyleSheets to each result's styleSheet (css-tag.ts, lines 174 to 177).

The sheet itself comes from that styleSheet getter. Here it is, as it is in Lit's source:

How a css result makes its sheet: css-tag.ts, lines 71 to 91, at lit 3.3.3TypeScript
get styleSheet(): CSSStyleSheet | undefined {
  // If `supportsAdoptingStyleSheets` is true then we assume CSSStyleSheet is
  // constructable.
  let styleSheet = this._styleSheet;
  const strings = this._strings;
  if (supportsAdoptingStyleSheets && styleSheet === undefined) {
    const cacheable = strings !== undefined && strings.length === 1;
    if (cacheable) {
      styleSheet = cssTagCache.get(strings);
    }
    if (styleSheet === undefined) {
      (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(
        this.cssText
      );
      if (cacheable) {
        cssTagCache.set(strings, styleSheet);
      }
    }
  }
  return styleSheet;
}

In plain words, line by line:

  1. Line 1 makes styleSheet a getter. It runs each time someone reads it.
  2. Line 4 takes the sheet this result made before, if there is one.
  3. Line 6 goes on only when the browser can adopt sheets and there is no sheet yet.
  4. Line 7 asks if the literal had no expressions. Then it has exactly one string, and its sheet can be filed under those strings.
  5. Lines 8 to 10 look for a sheet made earlier from the same literal.
  6. Lines 11 to 14 make a new CSSStyleSheet if none was found, and fill it with replaceSync().
  7. Lines 15 to 17 file the new sheet under the literal's strings. Line 20 returns the sheet.

So the sheet is made once, the first time an element needs it. Lit's comment above the getter says so: in practice, "stylesheets are not created until the first element instance is made" (lines 69 to 70).

Line 7 has a detail worth seeing. JavaScript hands a tag the same strings array each time the same literal runs (lesson 18.2). Lit files sheets under it in a WeakMap (line 39). Try it:

One literal, made twice, with and without an expressionPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><script type="module">  import { css } from "lit";  const plain = () => css`p { color: seagreen; }`;  const sized = (n) => css`p { margin: ${n}px; }`;  console.log(`Same result object: ${plain() === plain()}. Same sheet: ${plain().styleSheet === plain().styleSheet}`);  console.log(`With an expression, same sheet: ${sized(4).styleSheet === sized(4).styleSheet}`);</script>
ResultLoading…
  • Line 6 returns a new css result each time, from one literal with no expressions.
  • Line 7 does the same, but its literal has an expression.
  • Lines 8 and 9 compare two results, and the sheets they make.

It prints Same result object: false. Same sheet: true and With an expression, same sheet: false.

Why it matters: static styles run once per class, so a class gets one sheet either way. But a helper that builds css with an expression on every call makes a new sheet on every call.

In a browser without adoptedStyleSheets, adoptStyles() falls back. It adds one <style> element to each shadow root, with the same text (lines 178 to 189). Chrome, Firefox, and Safari all adopt sheets, so the fallback only runs in old versions:

Can you use variables in Lit's css tag?

Ravi wants the border width and the leaf green in variables, so he can change them in one place. Lit allows two kinds of values inside a css literal: other css results, and numbers (Lit). Try three kinds:

Playground: what can go inside css
A card whose border comes from two valuesPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-card>Sencha</tea-card><script type="module">  import { LitElement, html, css, unsafeCSS } from "lit";  const width = 4;  const leaf = css`seagreen`;  class TeaCard extends LitElement {    static styles = css`      :host { display: block; border: ${width}px solid ${leaf}; }    `;    render() {      return html`<slot></slot>`;    }  }  customElements.define("tea-card", TeaCard);  const card = document.querySelector("tea-card");  await card.updateComplete;  console.log(`Border: ${getComputedStyle(card).border}`);</script>
ResultLoading…
Try it yourself
A css result goes in as CSS text

It prints Border: 4px solid rgb(46, 139, 87). Lit copied the text of the css result, and the number 4, into the CSS.

Only line 8 changes. Pick each choice and read the console.
  • Line 7 is a number. Line 8 is the leaf green, and your choice changes only this line.
  • Line 11 puts both into the border.
  • Line 20 prints the card's border.

With a css result, it prints Border: 4px solid rgb(46, 139, 87). With unsafeCSS(), it prints the same. With a plain string, nothing prints, and the console shows Lit's error: Value passed to 'css' function must be a 'css' function result: seagreen. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.

The check lives in textFromCSSResult() (css-tag.ts, lines 106 to 119). A css result gives its cssText. A number goes in as it is. Anything else throws (lines 113 to 117). Lit's docs give the reason: the rule protects apps from harmful styles that come from places like URL parameters or database values (Lit).

A second rule follows from static. Expressions in static styles run once, when the class is made. Lit's docs say they are "evaluated once, then reused for all instances" (Lit). So a value can't change from one item to the next. The per-instance section shows what to use instead.

Why did a CSS escape remove all my styles?

CSS can write a character by its code: \2022 is a bullet. In a css literal, that backslash belongs to JavaScript first.

A CSS escape written three waysPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><script type="module">  import { css } from "lit";  const one = css`li::before { content: "\2022"; }`;  const two = css`li::before { content: "\\2022"; }`;  const three = css`li::before { content: "\u2022"; }`;  for (const result of [one, two, three]) console.log(String(result.cssText));</script>
ResultLoading…
  • Line 6 writes the escape as CSS would. Line 7 doubles the backslash.
  • Line 8 uses JavaScript's own escape, \u2022. Line 9 prints each result's cssText.

It prints undefined, then li::before { content: "\2022"; }, then li::before { content: "•"; }.

\2 isn't a valid escape in JavaScript. In a plain template literal, it's a SyntaxError. In a tagged template, JavaScript allows it and hands the tag undefined in place of that text (MDN). So the css tag gets no CSS at all. Every rule in that literal is gone, and nothing throws. Lit's docs name both fixes: \\2022 or \u2022 (Lit). The JavaScript path explains backslashes in template literals.

What does unsafeCSS do in Lit?

unsafeCSS(value) turns any value into a css result, so the css tag takes it (css-tag.ts, lines 128 to 133). It doesn't check the value. It only wraps it.

Lit's docs allow it for one case: a value from a fully trusted source, such as a constant in your own code (Lit). The comment above it in Lit's source says why. Untrusted CSS can "phone home or exfiltrate data to an attacker controlled site" (lines 124 to 126).

Leaf and Kettle now sells its cards to other tea shops. Each shop owner picks an accent color in a settings form. What if the code hands that text to unsafeCSS()?

Playground: unsafeCSS() with your own value and with typed text
A card whose accent goes through unsafeCSS()Pop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-card>Sencha</tea-card><script type="module">  import { LitElement, html, css, unsafeCSS } from "lit";  const accent = "seagreen"; // written in your own code  class TeaCard extends LitElement {    static styles = css`      :host { display: block; border: 4px solid ${unsafeCSS(accent)}; }    `;    render() {      return html`<p><slot></slot></p>`;    }  }  customElements.define("tea-card", TeaCard);  const card = document.querySelector("tea-card");  await card.updateComplete;  for (const rule of card.shadowRoot.adoptedStyleSheets[0].cssRules) console.log(rule.cssText);  console.log(`p display: ${getComputedStyle(card.shadowRoot.querySelector("p")).display}`);</script>
ResultLoading…
Try it yourself
A constant from your own code

It prints one rule, :host { display: block; border: 4px solid seagreen; }, and p display: block. Sencha shows, with a green border.

Only line 7 changes. Pick each choice and read the rules the console prints.
  • Line 7 is the accent. Line 10 puts it in the border, through unsafeCSS().
  • Line 19 prints every rule in the card's sheet. Line 20 prints how the name's paragraph displays.

With your own constant, it prints one rule and p display: block. With the typed text, it prints two rules: the border, then p { display: none; }. It ends with p display: none, and the name is gone.

Look at the typed text: seagreen; } p { display: none. Its } ended the :host rule. The rest became a brand new rule. Here it only hides a name. Lit's docs warn that harmful CSS can also "phone home", by adding an image URL that points to another server (Lit).

Real-life analogyA stranger writing on the menu board

Only Asha's sign painter writes on the menu board. A customer asks to add a note about their favourite tea. If the painter copied it word for word, it could say anything, even "Closed today" across the whole board. So the board has small holders instead, each for one price card.

In real life: The shop's own sign painter
In JavaScript: css results and numbers from your own code
In real life: Copying a stranger's note onto the board
In JavaScript: Typed text passed through unsafeCSS()
In real life: "Closed today" written across the board
In JavaScript: A typed } that ends the rule and adds a new one
In real life: A small holder for one price card
In JavaScript: A custom property that holds one value

Where should typed text go instead?

Put it in a custom property. A custom property is a CSS variable, like --tea-accent, that the card's CSS reads with var() (lesson 12.1). Here the page sets it on the card:

The same typed text, as a custom propertyPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-card>Sencha</tea-card><script type="module">  import { LitElement, html, css } from "lit";  const accent = "seagreen; } p { display: none"; // typed in a settings form  class TeaCard extends LitElement {    static styles = css`      :host { display: block; border: 4px solid var(--tea-accent, gray); }    `;    render() {      return html`<p><slot></slot></p>`;    }  }  customElements.define("tea-card", TeaCard);  const card = document.querySelector("tea-card");  card.style.setProperty("--tea-accent", accent);  await card.updateComplete;  console.log(`--tea-accent: "${card.style.getPropertyValue("--tea-accent")}"`);  console.log(`p display: ${getComputedStyle(card.shadowRoot.querySelector("p")).display}`);</script>
ResultLoading…
  • Line 7 is the same typed text.
  • Line 10 reads --tea-accent, with gray as the fallback. Line 18 sets the typed text as its value.
  • Line 20 prints what the property holds. Line 21 prints the paragraph's display.

It prints --tea-accent: "" and p display: block. Chrome refused the value, so the border falls back to gray, and the name stays.

Why did Chrome refuse it? A custom property's value may not hold an unmatched } or a ; outside brackets (CSS Custom Properties, section 2.1). The typed text has both. Even a value Chrome takes stays one value for one property. It can't close the rule or start a new one.

At the top, a card with the typed text seagreen; } p { display: none, labeled what the shop owner typed. An arrow goes down left, through unsafeCSS(), to two cards: :host { … seagreen; } and p { display: none; }, labeled a new rule hides the name. An arrow goes down right, as a custom property, to two cards: --tea-accent: empty quotes, and p display: block, labeled the value is refused.what the shop owner typedseagreen; } p { display: nonethrough unsafeCSS():host { … seagreen; }p { display: none; }a new rule hides the nameas a custom property--tea-accent: ""p display: blockthe value is refused
Through unsafeCSS(), the typed } ends the rule, and the rest becomes a new rule. As a custom property, the same text is one value, and Chrome refuses it.

Why it matters: keep unsafeCSS() for values you wrote yourself. Anything a person typed goes in a custom property.

How do you share styles between Lit components?

The card and the button both need the shop's font and ink color. Lit's way is a plain JavaScript module that exports a css result. Each component imports it and lists it in static styles (Lit). Lesson 12.6 did the same with a sheet made by hand.

A card and a button that import one css modulePop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-card>Sencha <tea-button>Add</tea-button></tea-card><div id="more" hidden></div><script type="module">  import { teaTokens } from "./tea-tokens.js";  import "./tea-card.js";  import "./tea-button.js";  const more = document.querySelector("#more");  for (let n = 1; n < 100; n++) more.append(document.createElement("tea-card"), document.createElement("tea-button"));  const all = [...document.querySelectorAll("tea-card, tea-button")];  await Promise.all(all.map((element) => element.updateComplete));  const [card, button] = all;  console.log(`Card starts with teaTokens: ${card.shadowRoot.adoptedStyleSheets[0] === teaTokens.styleSheet}`);  console.log(`Button starts with teaTokens: ${button.shadowRoot.adoptedStyleSheets[0] === teaTokens.styleSheet}`);  console.log(`Elements: ${all.length}. Sheet objects: ${new Set(all.flatMap((element) => element.shadowRoot.adoptedStyleSheets)).size}`);</script>
ResultLoading…
tea-tokens.js: the shared css resultJavaScript
import { css } from "lit";

export const teaTokens = css`
  :host {
    font: 16px Georgia, serif;
    color: var(--tea-color-ink, #222);
  }
`;
tea-card.js: the tokens first, then the card's own cssJavaScript
import { LitElement, html, css } from "lit";
import { teaTokens } from "./tea-tokens.js";

export class TeaCard extends LitElement {
  static styles = [
    teaTokens,
    css`
      :host { display: block; padding: 8px; border: 2px solid seagreen; border-radius: 8px; }
    `,
  ];

  render() {
    return html`<slot></slot>`;
  }
}

customElements.define("tea-card", TeaCard);
  • In the tea-tokens.js tab, line 3 exports teaTokens, one css result. Lines 4 to 7 set the font and the ink color on the host.
  • In the tea-card.js tab, line 2 imports it. Lines 5 to 10 make static styles an array: teaTokens on line 6, then the card's own css on lines 7 to 9. The tea-button.js tab does the same, with a rule for its button.
  • On the page, line 4 is a card with a button inside. Line 11 adds 99 more of each to the hidden box on line 5, so there are 200 elements.
  • Lines 15 and 16 check the first adopted sheet of the card and of the button. Line 17 counts the sheets in all 200 shadow roots.

It prints Card starts with teaTokens: true, Button starts with teaTokens: true, and Elements: 200. Sheet objects: 3.

Three sheets for 200 elements: teaTokens, the card's own, and the button's own. A module runs once, however many files import it (how modules load). So both classes hold the very same css result, and so the same sheet.

At the top, tea-tokens.js with a card teaTokens sheet. Two arrows go down to two crates. The left crate, a card's shadow root, holds two cards: 1: teaTokens and 2: card's own sheet. The right crate, a button's shadow root, holds 1: teaTokens and 2: button's own sheet. Label: the same teaTokens object in both.tea-tokens.jsteaTokens sheet1: teaTokens2: card's own sheeta card's shadow root1: teaTokens2: button's own sheeta button's shadow rootthe same teaTokens object in both
TeaCard and TeaButton both list the one teaTokens result first. So the first adopted sheet in every card and every button is the same object.

Lists can nest. Lit flattens the array and drops repeats, keeping the last copy of each (reactive-element.ts, lines 945 to 962). So a component can list whole groups of shared styles, even when two groups hold the same sheet.

Can static styles use a CSS file?

Yes, in browsers with CSS module scripts. An import with { type: "css" } gives you a CSSStyleSheet (lesson 11.6). Lit takes a sheet as it is, next to css results (css-tag.ts, lines 21 to 28).

A CSS file in static stylesPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-card>Sencha</tea-card><script type="module">  import { LitElement, html, css } from "lit";  import tokens from "./tea-tokens.css" with { type: "css" };  class TeaCard extends LitElement {    static styles = [tokens, css`:host { display: block; border: 2px solid seagreen; }`];    render() {      return html`<slot></slot>`;    }  }  customElements.define("tea-card", TeaCard);  const card = document.querySelector("tea-card");  await card.updateComplete;  console.log(`A CSSStyleSheet: ${tokens instanceof CSSStyleSheet}. Adopted as it is: ${card.shadowRoot.adoptedStyleSheets[0] === tokens}`);</script>
ResultLoading…

Line 7 imports the tea-tokens.css tab as a sheet. Line 9 lists it first, and line 17 checks what Lit adopted. It prints A CSSStyleSheet: true. Adopted as it is: true.

Chrome 123 and Firefox 147 support it, and Safari doesn't. Lesson 11.6 shows a fallback for Safari. Lit's cheat sheet lists other ways for teams that keep CSS in .css files (Lit). One is a build plugin that turns each file into a css module. Benny Powers's lit-css has plugins for Rollup, esbuild, webpack, Vite, and more (lit-css). Its README adds that a plain .css.js module, like tea-tokens.js, may be the better choice.

How do you inherit styles from a Lit superclass?

The shop wants a special card for the tea of the day: the same card, with a gold border. A subclass of TeaCard is the natural way. But when a subclass sets static styles, its field hides the parent's (static members and inheritance). Try three ways to write it:

Playground: a subclass's styles, with and without its parent's
A tea of the day card that extends TeaCardPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-card>Sencha</tea-card><tea-special-card>Gyokuro, the tea of the day</tea-special-card><script type="module">  import { css } from "lit";  import { TeaCard } from "./tea-card.js";  class TeaSpecialCard extends TeaCard {    static styles = [TeaCard.styles, css`:host { border-color: goldenrod; }`];  }  customElements.define("tea-special-card", TeaSpecialCard);  const special = document.querySelector("tea-special-card");  await special.updateComplete;  const style = getComputedStyle(special);  console.log(`Sheets: ${special.shadowRoot.adoptedStyleSheets.length}. Display: ${style.display}. Border width: ${style.borderTopWidth}`);</script>
ResultLoading…
Try it yourself
The parent's styles, then the subclass's

It prints Sheets: 3. Display: block. Border width: 2px. The special card has the tokens, the card's look, and its own gold border.

Only line 10 changes. Pick each choice and compare the two cards.
  • Line 8 imports TeaCard from the sharing section's tab. Line 9 extends it.
  • Line 10 is the subclass's styles, and your choice changes only this line.
  • Line 16 prints how many sheets the special card adopted, its display, and its border width.

With TeaCard.styles first, it prints Sheets: 3. Display: block. Border width: 2px. super.styles prints the same. With css alone, it prints Sheets: 1. Display: inline. Border width: 0px, and Gyokuro loses the padding, the border, and the shop's font.

A subclass's static styles replace its parent's. Lit doesn't add them up. List the parent's first, then your own, as Lit's docs show (Lit). super.styles reads the parent's field too. In TypeScript, the docs suggest naming the parent class instead, because the compiler doesn't always convert super.styles correctly. They also suggest typing the parent's field as CSSResultGroup, so a subclass may set an array.

TeaCard.styles is itself an array, so line 10 puts one array inside another. That's fine, because Lit flattens it. A list like [teaTokens, TeaCard.styles, gold] still adopts three sheets: the second teaTokens is dropped.

Real-life analogyA new counter's rule sheet

Asha opens a second counter for the tea of the day. She pins up the house rules, then her own note below them: gold cups at this counter. A new helper pins up only the note. That counter has gold cups, and no house rules at all.

In real life: The house rules
In JavaScript: TeaCard.styles
In real life: The new counter's own note
In JavaScript: The subclass's css
In real life: Pinning the rules, then the note below them
In JavaScript: [TeaCard.styles, css…]
In real life: Pinning only the note
In JavaScript: static styles = css… alone

Lesson 19.1's TeaElement put the parent's sheets first for you. Lit leaves it to each subclass, so a subclass can also drop a parent's styles on purpose.

How do you style one instance of a Lit component?

Static styles are the same for every item. That's what makes them cheap. So how does one item look different? With values that live on the element, not in the sheet. Here are two:

  • An attribute, matched by :host() in static styles (lesson 11.2).
  • A custom property that the page sets. Lit's docs call this theming (Lit).
Three menu items: plain, sold out, and in the evening areaPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><style>  .evening tea-menu-item { --tea-color-leaf: goldenrod; }</style><tea-menu-item name="Sencha"></tea-menu-item><tea-menu-item name="Gyokuro"></tea-menu-item><div class="evening">  <tea-menu-item name="Assam"></tea-menu-item></div><script type="module">  import "./tea-menu-item.js";  const items = document.querySelectorAll("tea-menu-item");  items[1].soldOut = true;  for (const item of items) {    await item.updateComplete;    const h3 = getComputedStyle(item.shadowRoot.querySelector("h3"));    console.log(`${item.name}: ${getComputedStyle(item).borderBottomColor}, ${h3.textDecorationLine}`);  }</script>
ResultLoading…
tea-menu-item.js: an attribute and a custom propertyJavaScript
import { LitElement, html, css } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = {
    name: {},
    soldOut: { type: Boolean, reflect: true, attribute: "sold-out" },
  };

  static styles = css`
    :host { display: block; border-bottom: 2px solid var(--tea-color-leaf, seagreen); }
    :host([sold-out]) h3 { text-decoration: line-through; }
    h3 { margin: 4px 0; font: bold 16px Georgia, serif; }
  `;

  render() {
    return html`<h3>${this.name}</h3>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • In the tea-menu-item.js tab, line 6 declares soldOut. reflect: true copies it to the sold-out attribute (lesson 20.2).
  • Line 10 draws the line in --tea-color-leaf, with seagreen as the fallback. Line 11 strikes through the name of a sold-out item.
  • On the page, line 5 sets --tea-color-leaf on items inside .evening. Line 15 sets Gyokuro's soldOut. Line 19 prints each item's line color and its name's decoration.

It prints Sencha: rgb(46, 139, 87), none, Gyokuro: rgb(46, 139, 87), line-through, and Assam: rgb(218, 165, 32), none.

Three items, one sheet, three looks. The sheet holds every rule already. The attribute and the custom property pick which rules match and which values they use. Why it matters: you can theme a whole area of a page, or mark one item, without a new sheet.

Real-life analogyA card on each table

Every table reads the same menu board. One table also has a small card on it: Reserved. The waiter reads the board for the menu, and the card for that one table. Nobody repaints the board for one table.

In real life: The menu board
In JavaScript: static styles, the same for every item
In real life: A small card on one table
In JavaScript: An attribute or a custom property on one element
In real life: "Reserved" on the card
In JavaScript: sold-out, matched by :host([sold-out])
In real life: Reading the board and the card together
In JavaScript: One rule, with a value that comes from the element

classMap and styleMap

Inside the template, Lit has two directives for the same job. A directive is a function that changes how one expression renders (lesson 20.4). classMap() adds and removes classes from an object. styleMap() sets inline styles from an object (Lit).

Two strength bars, drawn with classMap and styleMapPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-strength level="2"></tea-strength><tea-strength level="5"></tea-strength><script type="module">  import "./tea-strength.js";  for (const meter of document.querySelectorAll("tea-strength")) {    await meter.updateComplete;    const bar = getComputedStyle(meter.shadowRoot.querySelector("div"));    console.log(`Level ${meter.level}: ${bar.width} wide, ${bar.backgroundColor}`);  }</script>
ResultLoading…
tea-strength.js: a class and a custom property per instanceJavaScript
import { LitElement, html, css } from "lit";
import { classMap } from "lit/directives/class-map.js";
import { styleMap } from "lit/directives/style-map.js";

class TeaStrength extends LitElement {
  static properties = { level: { type: Number } };

  static styles = css`
    :host { display: block; width: 100px; margin: 8px 0; }
    .bar { --level: 0; height: 8px; width: calc(var(--level) * 20%); background: seagreen; }
    .strong { background: saddlebrown; }
  `;

  render() {
    const classes = { bar: true, strong: this.level >= 4 };
    return html`<div class=${classMap(classes)} style=${styleMap({ "--level": this.level })}></div>`;
  }
}

customElements.define("tea-strength", TeaStrength);
  • In the tea-strength.js tab, lines 2 and 3 import the two directives. Line 10 starts --level at 0, and makes the bar's width from it. Line 11 is a darker color for the class strong.
  • Line 15 builds the classes: bar always, and strong from level 4 up.
  • Line 16 binds classMap() to class and styleMap() to style. The "--level" key is in quotes, because it has dashes.
  • On the page, lines 4 and 5 are two bars. Line 11 prints each bar's width and color.

It prints Level 2: 40px wide, rgb(46, 139, 87) and Level 5: 100px wide, rgb(139, 69, 19).

Each directive must be the only expression in its attribute. Anywhere else, Lit throws: `classMap()` can only be used in the `class` attribute and must be the only part in the attribute. (class-map.ts, lines 38 to 41). styleMap() has its own (style-map.ts, lines 43 to 46). Lit's cheat sheet suggests classMap() for most conditional styles (Lit). Give styleMap() a custom property, as here, and the static CSS decides what the value does.

Can you put a style element in a Lit template?

Yes. A <style> element in render() works, and it can even hold expressions. Lit's docs keep it for styles that static styles can't handle (Lit). Here is what it costs, with the same 100 items:

Playground: 100 items with static styles or a style element
100 menu items, counting sheets and style elementsPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="menu"></div><script type="module">  import "./tea-menu-item.js";  const menu = document.querySelector("#menu");  for (let n = 1; n <= 100; n++) {    const item = document.createElement("tea-menu-item");    item.name = `Tea ${n}`;    menu.append(item);  }  const items = [...menu.children];  await Promise.all(items.map((item) => item.updateComplete));  const sheets = new Set(items.flatMap((item) => item.shadowRoot.adoptedStyleSheets));  const styles = items.flatMap((item) => [...item.shadowRoot.querySelectorAll("style")]);  console.log(`Adopted sheet objects: ${sheets.size}. Style elements: ${styles.length}`);</script>
ResultLoading…
Try it yourself
static styles: one sheet for the class

It prints Adopted sheet objects: 1. Style elements: 0. All 100 shadow roots adopt the one sheet Lit made for the class.

Only the tea-menu-item.js tab changes. Pick each choice and read the console.
  • The page is the overview's, with one more count.
  • Line 15 counts adopted sheet objects. Line 16 collects the style elements of all 100 shadow roots. Line 17 prints both.

With static styles, it prints Adopted sheet objects: 1. Style elements: 0. With the style element, it prints Adopted sheet objects: 0. Style elements: 100.

tea-menu-item.js: the CSS in a style elementJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {} };

  render() {
    return html`<style>
        :host { display: block; border-bottom: 1px solid seagreen; }
        h3 { margin: 4px 0; font: bold 16px Georgia, serif; }
      </style>
      <h3>${this.name}</h3>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);

In this tab, lines 7 to 10 are the style element, inside the template. Line 11 is the name. Each of the 100 items carries its own copy, like a printed menu on every table.

An expression inside a style element costs more again. When any text in a style element changes, the browser must parse the whole element again. Lit's docs call that "extremely inefficient" (Lit). If one instance needs a different value, a custom property is cheaper.

A <link rel="stylesheet"> in the template is worse. Lit's docs don't recommend it. The component can show unstyled content while the file loads, and the link's URL is relative to the main document, not to your module (Lit). Lesson 11.1 compared style and link elements in shadow roots.

Read each row across: what you write, what the browser keeps for 100 items, and what it's for.

Ways to style a Lit component
What you writeFor 100 items, the browser keepsUse it for
static styles = css…One sheet, adopted by all 100 shadow roots.Every style that is the same for each instance. Start here.
A shared css module in several classesOne sheet for every class that imports it.Tokens and rules that many components share.
unsafeCSS(value) inside cssOne sheet, like any static style.A trusted value from your own code. Never text someone typed.
A custom property, like --tea-color-leafNo new sheet. The page or a theme sets one value.Themes, and values that change per page area or per instance.
:host([sold-out]), classMap(), or styleMap()No new sheet. The rules are already in static styles.The state of one instance.
A <style> element in render()100 style elements, one in each shadow root.A fallback, when nothing above can say the style.
A <link rel="stylesheet"> in render()One link element in each shadow root.Lit's docs don't recommend it. It can flash unstyled content, and its URL is relative to the page.

How do you set shadowRootOptions in Lit?

Lit makes each shadow root with attachShadow(), using the class's static shadowRootOptions (reactive-element.ts, lines 1119 to 1124). The default is { mode: 'open' } (line 929). Set your own to add another option, such as delegatesFocus (Lit).

With delegatesFocus: true, a click on a part that can't take focus, or focus() on the host, moves focus to the first control inside (lesson 14.1). It works like a receptionist who walks every visitor straight to the right desk.

A search box whose shadow root delegates focusPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-search></tea-search><script type="module">  import { LitElement, html, css } from "lit";  class TeaSearch extends LitElement {    static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };    static styles = css`      :host { display: inline-block; padding: 4px; border: 2px solid gray; }      :host(:focus-within) { border-color: seagreen; }    `;    render() {      return html`<span>Find</span> <input aria-label="Find a tea">`;    }  }  customElements.define("tea-search", TeaSearch);  const search = document.querySelector("tea-search");  await search.updateComplete;  console.log(`Mode: ${search.shadowRoot.mode}. Delegates focus: ${search.shadowRoot.delegatesFocus}`);  search.addEventListener("focusin", () => console.log(`Focus is on: ${search.shadowRoot.activeElement.localName}`));</script>
ResultLoading…
  • Line 8 copies Lit's own options with the spread syntax, then adds delegatesFocus (object spread).
  • Line 11 draws a green border while focus is inside. Line 14 is the word Find and a text box.
  • Line 20 prints the root's mode and its delegatesFocus. Line 21 prints where focus lands.

It prints Mode: open. Delegates focus: true. Click the word Find, and it prints Focus is on: input. The border turns green.

Why the spread? Lit hands your object to attachShadow() as it is. Without a mode, attachShadow() throws a TypeError, and the component never draws. Exercise 6 has that bug.

How do you turn off shadow DOM in Lit?

A partner shop uses an old page builder. Its global stylesheet must reach inside every component, so they ask for Lit components without shadow DOM. Lit allows it through createRenderRoot(), the method that returns the node Lit renders into. The default makes the shadow root and adopts static styles. Return this instead, and Lit renders into the element's own children (Lit).

Playground: a note with and without a shadow root
A tip note on a page with its own stylesPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><style>  p { color: crimson; }</style><h3>Leaf and Kettle</h3><tea-note><b>Steep for 3 minutes.</b></tea-note><script type="module">  import "./tea-note.js";  const note = document.querySelector("tea-note");  await note.updateComplete;  const root = note.renderRoot;  console.log(`Shadow root: ${note.shadowRoot !== null}`);  console.log(`The note's p: ${getComputedStyle(root.querySelector("p")).color}`);  console.log(`The page's h3: ${getComputedStyle(document.querySelector("h3")).fontStyle}`);  console.log(`Nodes in the slot: ${root.querySelector("slot").assignedNodes().length}`);</script>
ResultLoading…
Try it yourself
The default: a shadow root

It prints Shadow root: true, The note's p: rgb(46, 139, 87), The page's h3: normal, and Nodes in the slot: 1. Each side keeps its own styles, and the slot shows Steep for 3 minutes. under the tip.

Only the tea-note.js tab changes: the light DOM choice adds lines 8 to 10. Pick each choice and read the console.
  • Line 5 is a page rule: every p is crimson. Line 7 is the page's own h3.
  • Line 8 is the note, with a b element inside for its slot.
  • Line 13 takes the note's renderRoot: its shadow root, or the note itself. Lines 14 to 17 print four facts.
tea-note.js: rendering into its own childrenJavaScript
import { LitElement, html, css } from "lit";

class TeaNote extends LitElement {
  static styles = css`
    p { color: seagreen; }
  `;

  createRenderRoot() {
    return this;
  }

  render() {
    return html`<style>h3 { font-style: italic; }</style>
      <h3>Tip</h3>
      <p>Use water at 80 °C.</p>
      <slot></slot>`;
  }
}

customElements.define("tea-note", TeaNote);

In this tab, lines 4 to 6 make p seagreen in static styles. Lines 8 to 10 return this from createRenderRoot(). Line 13 puts a style element in the template that makes h3 italic. Line 16 is the slot. The shadow root choice is the same tab without lines 8 to 10.

With a shadow root, it prints Shadow root: true, The note's p: rgb(46, 139, 87), The page's h3: normal, and Nodes in the slot: 1. With createRenderRoot() returning this, it prints Shadow root: false, The note's p: rgb(220, 20, 60), The page's h3: italic, and Nodes in the slot: 0.

Here is what the note lost:

  • Style scoping, both ways. The page's crimson reached the note's p. The note's italic rule styled the page's own heading.
  • Its static styles. Lit adopts them only in the default createRenderRoot(), so the seagreen rule is never used. The document's own adoptedStyleSheets stay empty too.
  • Its slot. Lit's cheat sheet says it plainly: without a shadow root, a slot doesn't work (Lit). The b element stays a plain child, above the tip, because Lit adds its template after the children already there.
  • DOM scoping. document.querySelector("p") now finds the note's p, like any other p on the page.
Two halves. Left, with a shadow root: a card, page p rule: crimson. Below it is a crate, shadow root, with two cards: note's p: seagreen, and slot: 1 node. Under the crate is a card, page h3: normal. Label: each side keeps its styles. Right, createRenderRoot() returns this: the same page card, with an arrow down into a crate, the note itself. It holds note's p: crimson, and slot: 0 nodes. An arrow goes out of it to a card, page h3: italic. Label: styles cross both ways.with a shadow rootpage p rule: crimsonnote's p: seagreenslot: 1 nodeshadow rootpage h3: normaleach side keeps its stylescreateRenderRoot() returns thispage p rule: crimsonnote's p: crimsonslot: 0 nodesthe note itselfpage h3: italicstyles cross both ways
With a shadow root, the page's p rule stays out and the note's h3 rule stays in. Without one, both rules cross, and the slot has nothing to show.
Real-life analogyA market stall with no walls

Leaf and Kettle opens a stall at the street market. It has no walls. Music from the next stall drifts in, and Asha's sign hangs over the whole lane. In the shop, the walls kept both apart.

In real life: The shop's walls
In JavaScript: The shadow root
In real life: Music from the next stall drifting in
In JavaScript: The page's p rule reaching the note
In real life: Asha's sign hanging over the whole lane
In JavaScript: The note's h3 rule styling the page

Lit's docs say it plainly: rendering into children "is generally not recommended". The element "will not have access to DOM or style scoping", and it can't compose elements into its internal DOM (Lit). The cheat sheet says when it may be worth it: to work with older systems or libraries that don't support shadow DOM (Lit). Then you style the component from the page. Lesson 12.4 shows how.

Building themed tea cards with shared Lit styles

Here is the card the shop now sells. Two Lit components, tea-card and tea-button, share three layers of styles:

  • the kit's base sheet from tea-kit/base.js, made by hand in lesson 12.6;
  • teaTokens, the css module from the sharing section;
  • each component's own css.
Three themed cards with shared stylesPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><style>  .evening { --tea-color-leaf: goldenrod; }</style><tea-card name="Sencha">Grassy and fresh. <tea-button>Add</tea-button></tea-card><tea-card name="Gyokuro" sold-out>Sweet and deep.</tea-card><div class="evening">  <tea-card name="Assam">Malty, for the evening. <tea-button>Add</tea-button></tea-card></div><script type="module">  import { base } from "./tea-kit/base.js";  import "./tea-card.js";  import "./tea-button.js";  const all = [...document.querySelectorAll("tea-card, tea-button")];  await Promise.all(all.map((element) => element.updateComplete));  const sheets = new Set(all.flatMap((element) => element.shadowRoot.adoptedStyleSheets));  console.log(`Elements: ${all.length}. Sheet objects: ${sheets.size}`);  console.log(`The kit's base sheet comes first: ${all.every((element) => element.shadowRoot.adoptedStyleSheets[0] === base)}`);  for (const card of document.querySelectorAll("tea-card")) {    const style = getComputedStyle(card);    console.log(`${card.name}: ${style.borderTopColor}, opacity ${style.opacity}`);  }</script>
ResultLoading…
tea-card.js: the kit's sheet, the tokens, and its own cssJavaScript
import { LitElement, html, css } from "lit";
import { base } from "./tea-kit/base.js";
import { teaTokens } from "./tea-tokens.js";

export class TeaCard extends LitElement {
  static properties = {
    name: {},
    soldOut: { type: Boolean, reflect: true, attribute: "sold-out" },
  };

  static styles = [
    base,
    teaTokens,
    css`
      :host { margin: 8px 0; padding: 8px; border: 2px solid var(--tea-color-leaf, seagreen); border-radius: var(--tea-radius, 8px); }
      :host([sold-out]) { opacity: 0.6; }
      h3 { margin: 0 0 4px; }
    `,
  ];

  render() {
    return html`<h3>${this.name}</h3><slot></slot>`;
  }
}

customElements.define("tea-card", TeaCard);
  • On the page, line 5 gives the evening area a gold accent. Lines 7 and 8 are two cards, and Gyokuro is sold out. Line 10 is a card in the evening area.
  • Line 13 imports the kit's base sheet, to compare. Line 18 collects every adopted sheet. Lines 19 and 20 print the count and check the order. Lines 21 to 24 print each card's border color and opacity.
  • In the tea-card.js tab, line 2 imports base from the kit. Lines 11 to 19 list base, teaTokens, and the card's own css, in that order.
  • Line 15 reads the accent from --tea-color-leaf. Line 16 fades a sold-out card. The tea-button.js tab lists the same two shared sheets, then its own.

It prints Elements: 5. Sheet objects: 4 and The kit's base sheet comes first: true. Then it prints Sencha: rgb(46, 139, 87), opacity 1, Gyokuro: rgb(46, 139, 87), opacity 0.6, and Assam: rgb(218, 165, 32), opacity 1.

Four sheets for five elements: the base, the tokens, the card's, and the button's. A sheet made by hand and a css result sit side by side in one list. The evening card is gold, and no sheet changed for it. Now sort some styles of your own:

Where does this style belong?
  • Every card's padding and rounded corners
  • The focus ring that every kit component uses
  • The bullet before each step of a recipe
  • A darker accent for the evening menu
  • The accent color a shop owner picks in a settings form
  • A sold-out card looks faded
  • A strength bar as wide as its level
  • The row of the tea someone picked
Try it yourself
0 of 8 correct

Put each style where it belongs: in static styles, in a custom property the page sets, or in an attribute, classMap, or styleMap.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "Every instance gets its own copy of static styles." No. Lit makes one sheet for the class, and every shadow root adopts it. 100 items printed Sheet objects: 1.
  • "You can put any variable inside css." No. Only css results and numbers go in. A plain string throws Lit's error.
  • "unsafeCSS() makes a value safe." No. It skips the check. Typed text closed the rule and hid the name.
  • "A subclass adds its styles to its parent's." No. It replaces them. List TeaCard.styles or super.styles first.
  • "A style element in render() costs the same as static styles." No. 100 items held 100 style elements, where static styles held one adopted sheet.
  • "Returning this from createRenderRoot() keeps the static styles." No. Lit adopts them only into the shadow root it makes. Without one, they're never used, and slots stay empty.
  • ":host-context() is the way to style a component by its ancestor." No. Only Chrome supports it, and the CSS Working Group resolved to drop it (lesson 11.2). Set a custom property on the ancestor, as the evening area did.
  • "A CSS escape like \2022 throws an error." No. In Chrome, nothing throws. The css tag gets undefined, and the whole literal's CSS is lost.

Practice exercises

Exercise 1 · Warm-upPredict the sheets for four cards and two buttons

This page uses the sharing section's three tabs. Read it without running it. What does the console print?

<script type="importmap">
  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<tea-card>Sencha <tea-button>Add</tea-button></tea-card>
<tea-card>Assam <tea-button>Add</tea-button></tea-card>
<tea-card>Gyokuro</tea-card>
<tea-card>Oolong</tea-card>
<script type="module">
  import "./tea-card.js";
  import "./tea-button.js";
  const all = [...document.querySelectorAll("tea-card, tea-button")];
  await Promise.all(all.map((element) => element.updateComplete));
  console.log(`Sheet objects: ${new Set(all.flatMap((element) => element.shadowRoot.adoptedStyleSheets)).size}`);
</script>

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict a light DOM paragraph's color

    Read the page without running it. What color does the console print for the tip's paragraph?

    <script type="importmap">
      { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
    </script>
    <style>
      p { color: crimson; }
    </style>
    <tea-tip></tea-tip>
    <script type="module">
      import { LitElement, html, css } from "lit";
      class TeaTip extends LitElement {
        static styles = css`p { color: seagreen; }`;
        createRenderRoot() {
          return this;
        }
        render() {
          return html`<p>Warm the pot first.</p>`;
        }
      }
      customElements.define("tea-tip", TeaTip);
      const tip = document.querySelector("tea-tip");
      await tip.updateComplete;
      console.log(getComputedStyle(tip.querySelector("p")).color);
    </script>

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFix a font size that throws

      The price tag never draws, and the console shows Lit's error. Fix the tea-price-tag.js tab. What does the console print then?

      <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p>Sencha: <tea-price-tag amount="4"></tea-price-tag></p><script type="module">  import "./tea-price-tag.js";  const tag = document.querySelector("tea-price-tag");  await tag.updateComplete;  console.log(`Font size: ${getComputedStyle(tag.shadowRoot.querySelector("b")).fontSize}`);</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeBring back the bullets

        The steps should start with green bullets, but the whole css literal is lost. Fix the tea-steps.js tab. What does the console print then?

        <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-steps></tea-steps><script type="module">  import "./tea-steps.js";  const steps = document.querySelector("tea-steps");  await steps.updateComplete;  const li = steps.shadowRoot.querySelector("li");  console.log(`Before each step: ${getComputedStyle(li, "::before").content}. List style: ${getComputedStyle(li).listStyleType}`);</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeGive each card its own accent

          Each card should use its own accent attribute for its border. The page throws a TypeError instead. Fix the tea-card.js tab. What does the console print for Assam then?

          <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-card accent="seagreen">Sencha</tea-card><tea-card accent="goldenrod">Assam</tea-card><script type="module">  import "./tea-card.js";  for (const card of document.querySelectorAll("tea-card")) {    await card.updateComplete;    console.log(`${card.textContent}: ${getComputedStyle(card.shadowRoot.querySelector(".card")).borderTopColor}`);  }</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeMake the search box delegate focus

            The search box never draws. Fix the tea-search.js tab, then click the word Find. What does the console print?

            <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-search></tea-search><script type="module">  import "./tea-search.js";  const search = document.querySelector("tea-search");  search.addEventListener("focusin", () => console.log(`Focus is on: ${search.shadowRoot.activeElement.localName}`));</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The styles in Lit quiz · 8 questionsScore: first tries count
              1. Question 1 of 8This page makes 100 menu items. What does its first console line print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                <script type="importmap">
                  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
                </script>
                <div id="menu"></div>
                <script type="module">
                  import { TeaMenuItem } from "./tea-menu-item.js";
                  const menu = document.querySelector("#menu");
                  for (let n = 1; n <= 100; n++) {
                    const item = document.createElement("tea-menu-item");
                    item.name = `Tea ${n}`;
                    menu.append(item);
                  }
                  const items = [...menu.children];
                  await Promise.all(items.map((item) => item.updateComplete));
                  const sheets = new Set(items.flatMap((item) => item.shadowRoot.adoptedStyleSheets));
                  console.log(`Items: ${items.length}. Sheet objects: ${sheets.size}`);
                  console.log(`It is TeaMenuItem.styles.styleSheet: ${sheets.has(TeaMenuItem.styles.styleSheet)}`);
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 8Which values may go inside ${} in a css literal?

                Choose an answer to see the explanation.

              3. Question 3 of 8A shop owner types an accent color into a settings form. How should the card use it?

                Choose an answer to see the explanation.

              4. Question 4 of 8In this page, the subclass writes static styles = css:host { border-color: goldenrod; } alone. What happens?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                <script type="importmap">
                  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
                </script>
                <tea-card>Sencha</tea-card>
                <tea-special-card>Gyokuro, the tea of the day</tea-special-card>
                <script type="module">
                  import { css } from "lit";
                  import { TeaCard } from "./tea-card.js";
                  class TeaSpecialCard extends TeaCard {
                    static styles = css`:host { border-color: goldenrod; }`;
                  }
                  customElements.define("tea-special-card", TeaSpecialCard);
                  const special = document.querySelector("tea-special-card");
                  await special.updateComplete;
                  const style = getComputedStyle(special);
                  console.log(`Sheets: ${special.shadowRoot.adoptedStyleSheets.length}. Display: ${style.display}. Border width: ${style.borderTopWidth}`);
                </script>

                Choose an answer to see the explanation.

              5. Question 5 of 8What happens to a component whose createRenderRoot() returns this?

                Choose an answer to see the explanation.

              6. Question 6 of 8What does cssli::before { content: "\2022"; } give you in Chrome?

                Choose an answer to see the explanation.

              7. Question 7 of 8Why write static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }?

                Choose an answer to see the explanation.

              8. Question 8 of 8A card and a button both list the same teaTokens css result. How many tokens sheets does the page hold?

                Choose an answer to see the explanation.

              Key takeaways

              • Put a Lit component's CSS in static styles, written with the css tag.
              • Lit makes one CSSStyleSheet per css result, once, and every instance's shadow root adopts it.
              • Only css results and numbers go inside css. A plain string throws Lit's error.
              • unsafeCSS() skips that check. Use it for your own constants, never for typed text.
              • Share styles with a module that exports a css result. Every class that imports it adopts the same sheet.
              • A subclass's styles replace its parent's. List TeaCard.styles or super.styles first.
              • Style one instance with attributes, custom properties, classMap, and styleMap, not with a new sheet.
              • A style element in render() puts a copy in every instance. Keep it as a fallback.
              • Set shadowRootOptions with a spread of Lit's own, so the mode stays.
              • createRenderRoot() returning this loses scoping, static styles, and slots. Lit generally doesn't recommend it.

              Remember the one-liner.
              Static styles are one menu board on the wall. Everything that changes per table goes on the table's own card.

              Sources

              The facts on this page come from these docs, specifications, and source files:

              Support data comes from MDN's browser-compat-data.

              Coming next: Events in Lit, the next lesson of the Lit stage. It covers listening with @event in a template, and dispatching events from Lit components.

              CompleteFrontend Clear concepts. Working examples.