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.
- 01Style a Lit component the fast wayPut CSS in
static styleswith thecsstag, and know why 100 instances share one stylesheet. - 02Share styles safelyShare a
cssmodule between components, keep a parent's styles in a subclass, and keep typed text out ofunsafeCSS. - 03Style one instance, or skip shadow DOMUse custom properties,
:host()attributes,classMap, andstyleMap. SetshadowRootOptions, and know whatcreateRenderRoot()returningthistakes 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:
<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>- Lines 1 to 3 are the import map from lesson 20.1. The name
litmeans 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:
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
cssfrom Lit, next toLitElementandhtml. - 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.
Sheet objects: 1. Four of the 100 roots are drawn.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
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:
- When the class is made,
cssjoins its strings into one text,cssText(css-tag.ts, lines 143 to 159). - When you define the element, the browser reads
observedAttributes. Lit's getter for it runsfinalize()once for the class (reactive-element.ts, lines 659 to 669). It turns static styles into a list,elementStyles(line 899). - Each new element calls
createRenderRoot(). It attaches a shadow root and callsadoptStyles()with that list (lines 1119 to 1130). adoptStyles()sets the root'sadoptedStyleSheetsto each result'sstyleSheet(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:
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:
- Line 1 makes
styleSheeta getter. It runs each time someone reads it. - Line 4 takes the sheet this result made before, if there is one.
- Line 6 goes on only when the browser can adopt sheets and there is no sheet yet.
- Line 7 asks if the literal had no expressions. Then it has exactly one string, and its sheet can be filed under those strings.
- Lines 8 to 10 look for a sheet made earlier from the same literal.
- Lines 11 to 14 make a new
CSSStyleSheetif none was found, and fill it withreplaceSync(). - 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:
<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>- 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:
<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>It prints Border: 4px solid rgb(46, 139, 87). Lit copied the text of the css result, and the number 4, into the CSS.
- 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.
<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>- 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'scssText.
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()?
<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>It prints one rule, :host { display: block; border: 4px solid seagreen; }, and p display: block. Sencha shows, with a green border.
- 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).
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:
<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>- 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.
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 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:
<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>It prints Sheets: 3. Display: block. Border width: 2px. The special card has the tokens, the card's look, and its own gold border.
- 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.
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).
<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>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: truecopies it to thesold-outattribute (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-leafon items inside.evening. Line 15 sets Gyokuro'ssoldOut. 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.
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).
<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>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
--levelat 0, and makes the bar's width from it. Line 11 is a darker color for the classstrong. - Line 15 builds the classes:
baralways, andstrongfrom level 4 up. - Line 16 binds
classMap()toclassandstyleMap()tostyle. 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:
<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>It prints Adopted sheet objects: 1. Style elements: 0. All 100 shadow roots adopt the one sheet Lit made for the class.
- 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.
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.
| What you write | For 100 items, the browser keeps | Use 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 classes | One sheet for every class that imports it. | Tokens and rules that many components share. |
unsafeCSS(value) inside css | One sheet, like any static style. | A trusted value from your own code. Never text someone typed. |
A custom property, like --tea-color-leaf | No 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.
<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>- 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).
<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>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.
- 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.
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 ownadoptedStyleSheetsstay 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.
p rule stays out and the note's h3 rule stays in. Without one, both rules cross, and the slot has nothing to show.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.
<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>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
basefrom the kit. Lines 11 to 19 listbase,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:
- 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
Put each style where it belongs: in static styles, in a custom property the page sets, or in an attribute, classMap, or styleMap.
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.stylesorsuper.stylesfirst. - "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
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><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>It prints Sheet objects: 3. The four cards share the teaTokens sheet and the card's sheet. The two buttons share the same teaTokens sheet and the button's sheet.
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><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>It prints rgb(220, 20, 60), the page's crimson. With no shadow root, Lit adopts no static styles, and the page's p rule styles the tip's p like any other.
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><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>Lines 3 and 9 of the tea-price-tag.js tab change. Line 3 makes size the number 18, and line 9 adds px after it. The css tag takes numbers, so the console prints Font size: 18px.
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><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>Only line 6 of the tea-steps.js tab changes: \2022 becomes \\2022. Now JavaScript keeps one backslash for CSS, the literal has its text again, and the console prints Before each step: "• ". List style: none.
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><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>Only the tea-card.js tab changes. A new line 2 imports styleMap. Line 8 reads var(--accent, gray). Line 12 sets --accent on the div from this.accent. Each card now has its own value, so the console prints Assam: rgb(218, 165, 32).
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><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>Only line 4 of the tea-search.js tab changes. The spread copies mode: 'open', so attachShadow() works, and delegatesFocus is added. Click Find, and the console prints Focus is on: input.
Check your understanding
Question 1 of 8This page makes 100 menu items. What does its first console line print?
Read the code, then predict<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.
Question 2 of 8Which values may go inside ${} in a css literal?
Choose an answer to see the explanation.
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.
Question 4 of 8In this page, the subclass writes static styles = css
:host { border-color: goldenrod; }alone. What happens?Read the code, then predict<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.
Question 5 of 8What happens to a component whose createRenderRoot() returns this?
Choose an answer to see the explanation.
Question 6 of 8What does css
li::before { content: "\2022"; }give you in Chrome?Choose an answer to see the explanation.
Question 7 of 8Why write static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }?
Choose an answer to see the explanation.
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:
- Styles, Lit.
- css-tag.ts, at lit 3.3.3, Lit.
- reactive-element.ts, at lit 3.3.3, Lit.
- Using shadow DOM, MDN.
- Template literals, MDN.
- CSS Custom Properties for Cascading Variables, Level 1, W3C.
- The Lit Cheat Sheet, Elliott Marquez, Lit.
- import with, MDN.
- lit-css README, Benny Powers.
- Built-in directives, Lit.
- class-map.ts, at lit 3.3.3, Lit.
- style-map.ts, at lit 3.3.3, Lit.
- Working with Shadow DOM, Lit.
- Dropping :host-context(), a resolution, CSS Working Group.
- browser-compat-data, MDN.
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.