completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Organizing component CSS

Learn how to organize CSS for web components: design tokens on :root, one shared base sheet, and cascade layers in every shadow root, with low specificity.

By the end, you can
  • 01
    Split a kit's CSS into three tiersKeep design tokens on the page's :root, shared rules in one base sheet, and each component's look in its own sheet.
  • 02
    Share and order the sheetsExport one base sheet from a module, adopt it first, and start every sheet with @layer base, component, state;.
  • 03
    Keep selectors lightUse one class or tag per selector, skip IDs, and wrap base rules in :where() so any rule can win over them.

How do you organize CSS for web components?

Leaf and Kettle wants a new green. Ravi looks after the shop's tea kit, so he searches it for seagreen. He finds it in the card, the quantity, the panel, the tabs, and light.css. He also finds button { font: inherit; } copied into the card and the quantity. One small change means a hunt through the whole kit. How should a kit's CSS be laid out, so one change is one edit?

Split it into three tiers. Design tokens are the shared values, kept as custom properties on the page's :root. A base sheet holds the rules every component needs, and every component adopts it first. Each component's own sheet comes last. Start every sheet with @layer base, component, state;, and keep selectors short.

Here are all three tiers in one small page, with two components:

Tokens, a base sheet, and two componentsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tokens.css"><tea-badge>Organic</tea-badge><tea-card></tea-card> <script type="module">  import "./tea-card.js";  import "./tea-badge.js";  const card = document.querySelector("tea-card").shadowRoot;  const badge = document.querySelector("tea-badge").shadowRoot;  console.log("Same base sheet?", card.adoptedStyleSheets[0] === badge.adoptedStyleSheets[0]);  console.log("Card border:", getComputedStyle(card.querySelector(".card")).borderTopColor);  console.log("Badge:", getComputedStyle(badge.host).backgroundColor);</script>
ResultLoading…
  • The tokens.css tab sets two values on :root: the leaf green and the corner radius.
  • The base.js tab makes one sheet and exports it. Line 3 sets the host's box sizing. Line 4 lets buttons use the page's font.
  • In the tea-card.js tab, line 1 imports that sheet. Line 6 reads both tokens. Line 13 adopts the base sheet, then the card's own. The tea-badge.js tab does the same.
  • On the page, line 1 links the tokens. Lines 10 to 12 print what each component got.

It prints Same base sheet? true, Card border: rgb(46, 139, 87), and Badge: rgb(46, 139, 87). Both components hold the very same base sheet object. Both read seagreen from one line. Press Edit & run and change line 2 of tokens.css to teal. Both print rgb(0, 128, 128), and no component file changed.

Three rows. Row 1, Tokens: a card reading tokens.css: --tea-color-leaf, --tea-radius on :root. Row 2, Base: a card reading base.js: one sheet object. Row 3, Components: two windows, tea-card and tea-badge. An arrow goes from the base card into each window. Inside each window are two cards in order: base, then own sheet. At the bottom: each shadow root adopts the base sheet first, then its own.1. Tokenstokens.css: --tea-color-leaf, --tea-radius on :root2. Basebase.js: one sheet object3. Componentstea-cardbaseown sheettea-badgebaseown sheetEach shadow root adopts the base sheet first, then its own
The tokens sit on the page's :root and inherit into every component. The base sheet is one object, and both shadow roots adopt it before their own sheet.
Real-life analogyPaint swatches, shelving, and displays

Leaf and Kettle keeps one swatch card with its colors. Every display is painted from it. All the displays stand on the same shelving. Each display then has its own look. To repaint the shop, you change the swatch, not every display.

In real life: The swatch card with the shop's colors
In CSS: tokens.css, custom properties on :root
In real life: The shelving every display stands on
In CSS: The base sheet every component adopts first
In real life: Each display on the shelves
In CSS: One component's own sheet
In real life: Repainting from a new swatch
In CSS: Changing one token
The main idea

A component library keeps its CSS in three tiers. Tokens live on the page's :root. One base sheet is shared by every component. Each component adds its own sheet after it. The same @layer line orders them in every shadow root.

How do design tokens work with web components?

A design token is a design choice with a name. "The leaf green is seagreen" is a token. So is "corners are 8px round". On the web, a token becomes a custom property on :root, like --tea-color-leaf.

Why :root? Custom properties inherit, and they cross the shadow boundary, as lesson 12.1 showed. A value on :root reaches every element on the page, so it reaches every shadow root too.

Global tokens and component properties

A kit uses three kinds of names. Each has its own job:

A token, a component property, and a private nameCSS
:root { --tea-color-leaf: seagreen; }

tea-card.special { --tea-card-accent: sienna; }

:host { --_accent: var(--tea-card-accent, var(--tea-color-leaf)); }
  • Line 1 is a global token. It starts with the kit's prefix and says what it is: --tea-color-leaf. Every component may use it.
  • Line 3 sets a component property, --tea-card-accent. Lesson 12.1 named it after the card. Only the card reads it, and the page sets it to change one kind of component.
  • Line 5 is inside the card. Its private name, --_accent, takes the card's property if the page set it, and the token if not.

Try it. Change what the page sets:

Playground: which name does the card use?
Two cards on a page that links tokens.cssPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tokens.css"><style>/* The page sets nothing. */</style><tea-card>Green tea</tea-card><tea-card class="special">Oolong</tea-card> <script type="module">  import "./tea-card.js";  for (const card of document.querySelectorAll("tea-card")) {    const box = card.shadowRoot.querySelector(".card");    console.log(card.textContent, getComputedStyle(box).borderTopColor);  }</script>
ResultLoading…
Try it yourself
Both cards use the token

It prints Green tea rgb(46, 139, 87) and Oolong rgb(46, 139, 87). Neither card has --tea-card-accent, so line 6 of the tab falls back to --tea-color-leaf. tokens.css sets it to seagreen on :root, and both cards inherit it.

Only line 2 of the page changes: what the page sets on top of tokens.css. Line 6 of the tea-card.js tab reads the card's public name first, then the token.
  • Line 1 of the page links tokens.css, which sets the leaf green and the paper white on :root.
  • Line 2 is the only line that changes. Line 4 gives Oolong the class special.
  • In the tea-card.js tab, line 6 is the chain: var(--tea-card-accent, var(--tea-color-leaf)). Line 8 draws the border with it.

With only tokens.css, both cards print rgb(46, 139, 87). A new leaf token turns both teal. Setting --tea-card-accent on Oolong turns only Oolong sienna. var() takes its first name, and only falls back when that name has no value.

Why two names, and not one? The token changes the whole kit at once. The component property changes one kind of component and leaves the rest alone. A page needs both.

What if a page forgets tokens.css?

Then the chain runs out of names. This page doesn't link the file:

A card on a page with no tokensPop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card> <script type="module">  import "./tea-card.js";  const box = document.querySelector("tea-card").shadowRoot.querySelector(".card");  const style = getComputedStyle(box);  console.log("Border:", style.borderTopStyle, style.borderTopWidth);  console.log("Background:", style.backgroundColor);</script>
ResultLoading…
  • Line 1 is a card. No line links tokens.css.
  • Lines 7 and 8 print the card's border and background.

It prints Border: none 0px and Background: rgba(0, 0, 0, 0). The border is gone, and the background is clear. With no value anywhere in the chain, MDN says var() resolves to an invalid value. So the border and the background fall back to their defaults: no border, and nothing behind the text.

One fix is to end each chain with a plain value. Press Edit & run and change lines 5 and 6 of the tea-card.js tab to these:

Each chain ends with a plain valueCSS
--_bg: var(--tea-card-bg, var(--tea-color-paper, white));
--_accent: var(--tea-card-accent, var(--tea-color-leaf, seagreen));

Line 1 ends the background's chain with white. Line 2 ends the accent's chain with seagreen. Now it prints Border: solid 2px and Background: rgb(255, 255, 255).

Here is the whole chain the card follows now:

Three cards in a row with arrows between them: --tea-card-accent, labelled the card's public name; --tea-color-leaf, labelled the kit's token; seagreen, labelled a plain value. Above each arrow: not set? At the bottom: --_accent takes the first one that has a value.--tea-card-accentnot set?--tea-color-leafnot set?seagreenthe card's public namethe kit's tokena plain value--_accent takes the first one that has a value
The card asks for its own public name first. If the page didn't set it, the card uses the kit's token. If no token is set either, it uses the plain value at the end.
Real-life analogyThe house size and the customer's order

At Leaf and Kettle, a customer may ask for a cup size. If they don't, the barista uses the house size on the menu board. If the board is blank, she pours the size printed on the cup. She always pours something.

In real life: A customer who asks for a large cup
In CSS: --tea-card-accent, set on one card
In real life: The house size on the menu board
In CSS: --tea-color-leaf, the kit's token on :root
In real life: The size printed on the cup
In CSS: A plain value at the end, like seagreen
In real life: The cup the barista pours
In CSS: --_accent, the value the card uses

Material Web ends its chains with a plain value too. Its filled button reads its own name, --md-filled-button-container-color, then the system token, --md-sys-color-primary, then a plain color, #6750a4. Web Awesome's badge ends its chains with a token instead, like --wa-color-brand-fill-loud, and its install docs mark the theme stylesheet as required. Pick one, and say it in your docs.

Where do tokens come from?

A team can keep its tokens in a file of their own, and build the CSS from it. The W3C Design Tokens Community Group published the Design Tokens Format Module 2025.10. Its announcement calls it the first stable version. The format is JSON:

Two of the kit's tokens in the design tokens formatJSON
{
  "tea": {
    "color": {
      "leaf": {
        "$type": "color",
        "$value": { "colorSpace": "srgb", "components": [0.1804, 0.5451, 0.3412], "hex": "#2e8b57" }
      }
    },
    "radius": {
      "$type": "dimension",
      "$value": { "value": 8, "unit": "px" }
    }
  }
}
  • Groups nest: tea, then color, then leaf. An object with a $value is a token.
  • Line 5 says its $type is a color. Line 6 gives the color as numbers, with its hex code.
  • Lines 10 and 11 make the radius a dimension: the number 8, in px.

A build tool reads the file and writes CSS. Terrazzo's CSS plugin, for one, turns design tokens into CSS custom properties. Its docs show an option that names each one after the token's path, with dots turned into dashes:

Naming each custom property after its token's pathJavaScript
variableName: (token) => token.id.replace(/\./g, "-"),

Line 1 takes each token's id and swaps every dot for a dash. So tea.color.leaf becomes --tea-color-leaf. Built that way, the two tokens become this:

The two tokens as custom propertiesCSS
:root {
  --tea-color-leaf: #2e8b57;
  --tea-radius: 8px;
}

Line 2 holds the leaf green as its hex code, and line 3 holds the radius. Why it matters: the JSON file is one source for every tool. A design tool, the CSS, and a phone app can all read the same values.

How do you share styles between web components?

Some rules belong in every component. Page styles don't reach inside a shadow root, so each component needs its own copy. A base sheet is one shared copy of those rules. It holds things like these:

  • box-sizing: border-box, so padding and borders sit inside an element's size.
  • A small reset for the component's own elements. Buttons don't take the page's font. Chrome's styling guide calls this the most common miss, and font: inherit fixes it.
  • One focus ring, so every control in the kit looks the same when it has keyboard focus.
  • A display for the host, and :host([hidden]) { display: none !important; }, from lesson 11.4.

Lesson 11.5 made one sheet and shared it with every copy of one component. A shared style module goes one step further. It is a JavaScript module that makes the sheet and exports it. Every component imports it:

Two components import one base sheetPop out in the code editor (opens in a new tab)HTML
<style>  body { font: 16px Georgia, serif; }</style><tea-card></tea-card><tea-quantity></tea-quantity> <script type="module">  import "./tea-card.js";  import "./tea-quantity.js";  const hosts = document.querySelectorAll("tea-card, tea-quantity");  const bases = new Set([...hosts].map((host) => host.shadowRoot.adoptedStyleSheets[0]));  console.log("Base sheets:", bases.size);  for (const host of hosts) {    const button = host.shadowRoot.querySelector("button");    console.log(host.localName, getComputedStyle(host).display, getComputedStyle(button).fontFamily);  }</script>
ResultLoading…
  • In the base.js tab, line 1 makes the sheet and exports it. Lines 3 to 7 are the base rules from the list above.
  • In the tea-card.js tab, line 1 imports it, and line 12 adopts it before the card's own sheet. The tea-quantity.js tab does the same.
  • On the page, line 2 sets Georgia as the page's font.
  • Line 11 collects each component's first adopted sheet into a Set, which keeps one of each value. Line 15 prints each host's display and its button's font.

It prints Base sheets: 1, then tea-card block Georgia, serif and tea-quantity inline-flex Georgia, serif. Both buttons use the page's font, from one line in one file. Press Edit & run and delete line 6 of base.js. Both buttons go back to the browser's own button font.

Why is there one sheet, not two? A module runs once per page, however many files import it. The second import gets the module that already ran. Import and export covers modules, and lesson 11.6 saw the same rule for CSS files.

Real-life analogyOne recipe binder in the kitchen

Leaf and Kettle's kitchen keeps one recipe binder on a shelf. Every cook reads the same binder. When the head cook fixes a step, every cook sees the fix the next time they look.

In real life: The one binder on the kitchen shelf
In CSS: The base sheet object
In real life: The shelf where it lives
In CSS: The base.js module
In real life: Each cook who reads it
In CSS: Each shadow root that adopts it
In real life: Fixing a step once
In CSS: Changing the base sheet

A base sheet as a CSS file

The base sheet can also be a plain CSS file. Lesson 11.6 imported a CSS file as a sheet:

The base sheet as a CSS module scriptJavaScript
import base from "./base.css" with { type: "css" };

// In the constructor:
this.shadowRoot.adoptedStyleSheets = [base, sheet];

Line 1 gives back a CSSStyleSheet, one per file, like base.js does. Chrome and Firefox support it, and Safari doesn't. So use lesson 11.6's fallback, or keep the CSS in a JavaScript module, as the tea kit does.

How real libraries share their base styles

Web Awesome keeps its base rules in one small file, host.styles.ts. It sets box-sizing: border-box on the host, lets everything inside inherit it, and hides [hidden] with !important. Its base class puts those host styles first in every component's list of styles. Rob Eisenberg's post on global styles builds shared sheets once and adds them to each shadow root. Konnor Rogers suggests one shared sheet for utility classes too, imported by every component.

How do cascade layers organize a component library?

Look at the quantity in the last example. The base sheet says :host { display: block; }. The quantity's own sheet says inline-flex. Both selectors score the same, so the later sheet wins. That works, until a sheet lands in another order.

Lesson 11.4 met cascade layers: named groups of rules, put in order with @layer. A later layer beats an earlier one, whatever the selectors. And each shadow root keeps its own layers. A library can use that. Start every sheet, the base and each component's, with the same line:

  • base: the shared rules from the base sheet. They should lose to everything else.
  • component: the component's own look.
  • state: rules that should win, like a sold-out attribute, a custom state, or a style query.

Ravi has one more rule that turns the name crimson. Move it between the layers:

Playground: which layer is the rule in?
A card with a rule in each of its three layersPop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card><tea-card sold-out>Oolong</tea-card> <script type="module">  import "./tea-card.js";  for (const card of document.querySelectorAll("tea-card")) {    const h3 = card.shadowRoot.querySelector("h3");    console.log(card.textContent, getComputedStyle(h3).color);  }</script>
ResultLoading…
Try it yourself
Three layers, in order

It prints Green tea rgb(46, 139, 87) and Oolong rgb(160, 82, 45). The base layer's dim gray loses to the component layer's seagreen. The sold-out card also matches the state layer, which comes last, so Oolong is sienna.

Only line 12 of the tea-card.js tab changes: an extra rule that turns the name crimson, and the layer it goes in. Oolong is sold out.
  • In the base.js tab, line 3 sets the order. Line 6 puts a dim gray name in the base layer.
  • In the tea-card.js tab, line 5 sets the same order. Line 7 makes the name seagreen in component. Line 10 makes a sold-out card's name sienna in state.
  • Line 12 of the tab is Ravi's extra rule. On the page, line 2's Oolong is sold out.

With no extra rule, it prints Green tea rgb(46, 139, 87) and Oolong rgb(160, 82, 45). In base, the crimson rule changes nothing, though it comes last in the file. In component, it ties with line 7 and wins by coming later. Outside every layer, it beats them all, even state: both names turn crimson.

Two rules from MDN explain this. A rule in a named layer joins that layer, wherever it sits in the file. And normal styles outside any layer beat layered ones, whatever their specificity. So keep all of a component's CSS in layers. One unlayered line wins over every state.

Two halves. Left, inside tea-card's shadow root: four cards stacked, from the top: outside every layer, state, component, base. An arrow on the left points up from loses at the bottom to wins at the top. Right, the page's own layers: three cards from the top, state, component, base. Above them: a separate set, the same way up. Below them: changes nothing in the card. At the bottom: later layers win, and rules outside every layer win over all of them.Inside tea-card's shadow rootwinslosesoutside every layerstatecomponentbaseThe page's own layersstatecomponentbasea separate set, the same way upchanges nothing in the cardLater layers win. Rules outside every layer win over all of them.
Every sheet in the shadow root names base, component, state first, so that's the order. Rules outside every layer come after all three. The page's layers with the same names are a different set.
Real-life analogyStickers on a tea tin

A tea tin comes with a printed label. The shop sticks its price on top. When the tea runs out, a Sold out sticker goes on top of that. But a note taped to the glass in front covers them all.

In real life: The label printed on the tin
In CSS: The base layer
In real life: The shop's price sticker on top
In CSS: The component layer
In real life: A Sold out sticker on top of that
In CSS: The state layer
In real life: A note taped to the glass in front
In CSS: A rule outside every layer

The page can't change this order. Press Edit & run and add <style>@layer state, component, base;</style> as line 1 of the page. It prints the same. CSS Cascade 5 says layers belong to their context, so the page's order has no effect on layers with the same names in a shadow root. Adobe's tracker rates this as supported per spec in Chrome, Firefox, and Safari.

Why every sheet starts with the same line

Layers are sorted by where each name first appears. In a shadow root, the adopted sheets count in the order of the array. This card adopts its own sheet first, and neither sheet sets an order:

A card that adopts its own sheet before the basePop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card> <script type="module">  import "./tea-card.js";  const h3 = document.querySelector("tea-card").shadowRoot.querySelector("h3");  console.log("Name:", getComputedStyle(h3).color);</script>
ResultLoading…
  • In the base.js tab, line 4 puts a dim gray name in base.
  • In the tea-card.js tab, line 6 puts a seagreen name in component. Line 14 adopts the card's sheet first.

It prints Name: rgb(105, 105, 105), dim gray. component appeared first, so it became the earlier layer, and base won. Press Edit & run and add @layer base, component, state; as a new line 5 of the tab. It prints Name: rgb(46, 139, 87). Putting base first on line 14 fixes it too.

Why it matters: with the same line at the top of every sheet, the order holds whichever sheet comes first. A component author can't break it by adopting sheets in another order. Chrome's styling guide suggests layers like these, so a page's custom properties and parts still win as expected.

One more thing changes with layers: !important. For important rules, the earliest layer wins, as lesson 11.4 found. So the base sheet's :host([hidden]) { display: none !important; } beats an !important display in any later layer. A hidden component stays hidden.

How do you keep CSS specificity low?

Lesson 11.4 scored selectors with three numbers, like 0-1-0: IDs, then classes and attributes, then tags. That score is a selector's specificity. Layers decide first, so specificity only matters between rules in the same layer. It still matters there. Here are the scores Chrome's DevTools gives some selectors in a card:

Selectors in a card and their scores
SelectorScoreWhat counts
h30-0-1One tag.
.card h30-1-1One class and one tag.
.card .info h30-2-1Two classes and one tag.
#name1-0-0One ID. It outweighs any number of classes.
:where(.card .info h3)0-0-0Nothing. :where() always scores zero.
:host0-1-0One pseudo-class.
:host([kind="green"])0-2-0The pseudo-class, plus the attribute inside it.

Now see what a heavy base rule does. Neither sheet uses layers here, so specificity decides. Change the base rule's selector:

Playground: how heavy is the base rule?
A card that adopts a base sheet, then its ownPop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card> <script type="module">  import "./tea-card.js";  const h3 = document.querySelector("tea-card").shadowRoot.querySelector("h3");  console.log("Name:", getComputedStyle(h3).color);</script>
ResultLoading…
Try it yourself
The base rule is heavier

It prints Name: rgb(105, 105, 105). .card h3 scores 0-1-1, and the card's h3 scores 0-0-1. The base rule wins, though its sheet comes first. To beat it, the card would need a longer selector too.

Only line 3 of the base.js tab changes: the base rule's selector. Neither sheet uses layers here. The card's own rule is line 5 of the tea-card.js tab, h3 { color: seagreen; }.
  • Line 3 of the base.js tab is the base rule. Only its selector changes.
  • In the tea-card.js tab, line 5 is the card's own rule, h3 { color: seagreen; }. Line 12 adopts the base sheet first.

With .card h3 or #name, it prints Name: rgb(105, 105, 105). The base wins, though it comes first. With h3, the scores tie, and the card's later sheet wins. With :where(.card h3), the card wins too.

MDN says :where() always has 0 specificity. It matches like the selector inside it, but adds nothing to the score. That makes it a good wrapper for base rules: any rule can beat them.

Real-life analogyShelf labels in pencil

Ravi writes the shelf labels in pencil. Anyone can write over them in pen. One shelf has its label carved into the wood, and nobody can change it without a saw.

In real life: A label in pencil
In CSS: A base rule in :where(), scoring 0-0-0
In real life: Writing over it in pen
In CSS: Any component rule
In real life: A label carved into the wood
In CSS: An ID selector, like #name

So, for a library's selectors:

  • Use one class or one tag: .card, h3. Then any later rule of the same kind can win.
  • Skip IDs in styles. Keep them for links between elements, like the card's heading label.
  • Skip long chains like .card .info h3. They tie every rule to today's markup.
  • Wrap base rules in :where(), so they score zero.
  • Let the state layer win, instead of making a state's selector heavier.

Selectors on the host follow the same scores. :host scores 0-1-0, and :host([kind="green"]) scores 0-2-0. But no score beats the page: a page rule on the tag still wins over every normal :host rule, as lesson 11.4 showed. Web Awesome keeps its tokens light too. Its default theme sets them on :where(:root), inside a layer of its own, so any page rule can change them.

Reorganizing the tea kit's CSS

Before the kit changes, sort these pairs. Both rules style the same card. Which one wins?

Which rule wins?
  • @layer base { .card h3 { … } }, then @layer component { h3 { … } }
  • h3 { … } outside every layer, then @layer state { h3 { … } }
  • .card h3 { … }, then h3 { … }, both in @layer component
  • :where(.card h3) { … }, then h3 { … }, both in @layer component
  • @layer base { h3 { color: … !important; } }, then the same in @layer state
  • The page's tea-card { color: … }, then the card's @layer state { :host { color: … } }
Try it yourself
0 of 6 correct

Sort each pair of rules. Both set the color of the card's name.

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

Here is the kit in three tiers. First, the tokens, in a file the page links:

tea-kit/tokens.cssCSS
/* The tea kit's design tokens: the values every component shares. Link it in the page's head. */
@layer tea-kit {
  :root {
    --tea-color-leaf: seagreen;
    --tea-color-paper: white;
    --tea-color-stone: dimgray;
    --tea-radius: 8px;
    --tea-space: 8px;
  }
}
  • Line 2 puts the tokens in the tea-kit layer, like lesson 12.4's light.css. Any unlayered page rule beats them, wherever it sits.
  • Lines 4 to 8 are the kit's shared values: three colors, the corner radius from lesson 12.1, and an 8px spacing step.

Next, the base sheet, in its own module:

tea-kit/base.jsJavaScript
/** The kit's base styles: one sheet that every component adopts before its own sheet. */
export const base = new CSSStyleSheet();
base.replaceSync(`
  @layer base, component, state;
  @layer base {
    :host { display: block; box-sizing: border-box; }
    :host([hidden]) { display: none !important; }
    *, *::before, *::after { box-sizing: inherit; }
    :where(button) { font: inherit; }
    :where(:focus-visible) { outline: 2px solid var(--tea-color-leaf, seagreen); outline-offset: 2px; }
  }
`);
  • Line 4 sets the order. Lines 5 to 11 put every base rule in the base layer.
  • Line 6 makes every host a block. A component that wants another display sets it in its own layer.
  • Lines 9 and 10 wrap the button reset and the focus ring in :where(). Line 10 reads the leaf token.

tea-card, tea-quantity, and tea-badge each import base and adopt [base, sheet]. Here is the card's sheet now:

The style sheet in tea-kit/tea-card.jsCSS
@layer base, component, state;
@layer component {
  :host {
    container: tea-card / inline-size;
    --_bg: var(--tea-card-bg, var(--tea-color-paper, white));
    --_accent: var(--tea-card-accent, var(--tea-color-leaf, seagreen));
    --_radius: var(--tea-radius, 8px);
    --_space: var(--tea-space, 8px);
  }
  .card { display: flex; flex-direction: column; border: 2px solid var(--_accent); border-radius: var(--_radius); padding: var(--_space) 12px; background: var(--_bg); }
  h3 { margin: 0; color: var(--_accent); font-family: var(--tea-font-display, Georgia, serif); }
  p { margin: 4px 0 0; }
  h4 { margin: var(--_space) 0 0; }
  .buy { display: flex; align-items: center; gap: var(--_space); margin-top: var(--_space); }
  ::slotted(p) { margin: 4px 0 0; }
  @container (min-width: 320px) {
    .card { flex-direction: row; align-items: center; gap: 12px; }
    .info { flex: 1; }
    .buy { margin-top: 0; }
  }
}
@layer state {
  :host(:not(:state(has-notes))) h4 { display: none; }
  @container style(--tea-card-layout: compact) {
    .card { flex-direction: column; align-items: stretch; gap: 0; padding: 4px 8px; }
    .buy { margin-top: 4px; }
  }
}
  • Line 1 is the same order as the base sheet's.
  • Lines 5 and 6 are the chains: the card's public name, then the token, then the old value. Line 8 reads the spacing token.
  • Lines 2 to 21 are the card's look. The button rule is gone: the base sheet has it now. The row layout from lesson 12.5 stays here.
  • Lines 22 to 28 are the states. Line 23 hides the notes heading with a tag, not the old #notes. The compact style query no longer needs to come last in the file: its layer makes it win.

The quantity and the badge moved the same way. The badge reads the stone and paper tokens and the radius. Its kind colors went into state, and its hidden rule into the base sheet. The panel, the tabs, and the picker keep their own styles, and the same steps would move them too. Now one page changes the card, the quantity, and the badge with one token:

The kit with a teal leaf tokenPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><style>  :root { --tea-color-leaf: teal; }</style><tea-card name="Green tea" price="4"></tea-card><p><tea-badge kind="green">Organic</tea-badge> <tea-badge>New harvest</tea-badge></p> <script type="module">  import "./tea-kit/index.js";  const card = document.querySelector("tea-card");  const quantity = card.shadowRoot.querySelector("tea-quantity");  const hosts = [card, quantity, ...document.querySelectorAll("tea-badge")];  console.log("Base sheets:", new Set(hosts.map((host) => host.shadowRoot.adoptedStyleSheets[0])).size);  console.log("Border:", getComputedStyle(card.shadowRoot.querySelector(".card")).borderTopColor);  console.log("Name:", getComputedStyle(card.shadowRoot.querySelector("h3")).color);</script>
ResultLoading…
  • Line 1 links the kit's tokens. Line 3 changes one of them.
  • Line 12 collects the card, the quantity inside it, and both badges.
  • Lines 13 to 15 print the base sheets, the card's border, and its name.

It prints Base sheets: 1, Border: rgb(0, 128, 128), and Name: rgb(0, 128, 128). Four shadow roots share one base sheet, and one line turned the card teal. Click in the result and press Tab. The - button gets a teal ring, and so does the quantity around it. The Add button gets one too.

Without line 3, every card looks exactly as it did in lesson 12.5. Every color, size, and gap is the same, with or without tokens.css. Only box-sizing changed, and no box changed size. One thing is new on purpose: the kit's buttons show the sea green focus ring, not the browser's own.

Here are the three tiers side by side. Read each row across:

The three tiers of a component library's CSS
TierWhere it livesWhat it holdsWho changes it
Tokenstokens.css, linked by the page. Custom properties on :root.The kit's shared values: its colors, its corner radius, its spacing step.The page, to restyle every component at once.
Base sheetbase.js, one module. Every component adopts its sheet first.Rules every component needs: box sizing, button fonts, the focus ring, hidden.The kit's authors, once for every component.
Component sheetOne per component, in the component's own file.That component's look, and the states that change it.The component's author. The page uses its public custom properties and parts.

A page still styles one card with public custom properties and parts. Those stay the kit's styling API. The tiers are how the kit keeps its own CSS in order behind them.

Common mix-ups

  • "The page's @layer order also orders a component's layers." No. Each shadow root keeps its own layers. Layers with the same names in the page are a different set.
  • "Layering most of the CSS is enough." No. A normal rule outside every layer beats all the layered ones. One unlayered line wins over the state layer.
  • "Adopted sheets can come in any order." Only when each sheet starts with the full @layer line. Without it, the first name to appear becomes the earliest layer.
  • "Tokens can be shared through selectors, like :root h3." No. Page selectors don't reach inside a shadow root. Tokens travel as custom properties, which inherit.
  • "Each component that imports base.js gets its own copy." No. A module runs once per page, so every component adopts the same sheet object.
  • ":where() makes a rule weaker than the browser's own styles." No. It only sets the score to zero. Author styles still beat the browser's defaults.
  • "A heavier selector helps a state rule win." It can, but it ties the rule to the markup. Put the rule in the state layer instead.

Practice exercises

Answer first, then use the hints. The pages run live, so you can check yourself.

Exercise 1 · Warm-upPredict a later layer

The card's sheet has a plain h3 rule in state and a .card #name rule in component. What does the page print?

<tea-card>Green tea</tea-card> <script type="module">  import "./tea-card.js";  const h3 = document.querySelector("tea-card").shadowRoot.querySelector("h3");  console.log("Name:", getComputedStyle(h3).color);</script>
ResultLoading…

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

    Exercise 2 · Warm-upPredict an unlayered rule

    The card is sold out. Its sheet has an unlayered h3 rule and a sold-out rule in state. What does the page print?

    <tea-card sold-out>Green tea</tea-card> <script type="module">  import "./tea-card.js";  const h3 = document.querySelector("tea-card").shadowRoot.querySelector("h3");  console.log("Name:", getComputedStyle(h3).color);</script>
    ResultLoading…

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

      Exercise 3 · PracticeSet the layer order

      Oolong is sold out, but its name is seagreen. Add one line to the tea-card.js tab. What does the Oolong line print then?

      <tea-card>Green tea</tea-card><tea-card sold-out>Oolong</tea-card> <script type="module">  import "./tea-card.js";  for (const card of document.querySelectorAll("tea-card")) {    const h3 = card.shadowRoot.querySelector("h3");    console.log(card.textContent, getComputedStyle(h3).color);  }</script>
      ResultLoading…

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

        Exercise 4 · PracticeAdopt the base sheet

        The page's font is Georgia, but the quantity's buttons don't use it. Change the tea-quantity.js tab. What does the page print then?

        <style>  body { font: 16px Georgia, serif; }</style><tea-quantity></tea-quantity> <script type="module">  import "./tea-quantity.js";  const button = document.querySelector("tea-quantity").shadowRoot.querySelector("button");  console.log("Button font:", getComputedStyle(button).fontFamily);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeMove a state rule

          Oolong is sold out, but its name stays seagreen. Fix it without changing any selector. What does the Oolong line print then?

          <tea-card>Green tea</tea-card><tea-card sold-out>Oolong</tea-card> <script type="module">  import "./tea-card.js";  for (const card of document.querySelectorAll("tea-card")) {    const h3 = card.shadowRoot.querySelector("h3");    console.log(card.textContent, getComputedStyle(h3).color);  }</script>
          ResultLoading…

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

            Exercise 6 · ChallengePredict two important rules

            The card is hidden. Its base layer says display: none !important, and its state layer says display: block !important. What does the page print?

            <tea-card hidden>Green tea</tea-card> <script type="module">  import "./tea-card.js";  console.log("Display:", getComputedStyle(document.querySelector("tea-card")).display);</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask: which tier is this, which layer is it in, and what does its selector score?

              The organizing component CSS quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Where should a component library keep its design tokens, like --tea-color-leaf?

                Choose an answer to see the explanation.

              2. Question 2 of 7The page sets :root { --tea-color-leaf: teal; } and writes <tea-card style="--tea-card-accent: sienna">Oolong</tea-card>. The card's shadow root has this CSS. What color is Oolong's border?

                Read the code, then predictPop out in the code editor (opens in a new tab)CSS
                :host { --_accent: var(--tea-card-accent, var(--tea-color-leaf, seagreen)); }
                .card { border: 2px solid var(--_accent); }

                Choose an answer to see the explanation.

              3. Question 3 of 7Why does every sheet in the kit start with @layer base, component, state;?

                Choose an answer to see the explanation.

              4. Question 4 of 7What does this shadow root's sheet give the name?

                Read the code, then predictPop out in the code editor (opens in a new tab)CSS
                @layer base, component, state;
                @layer state { h3 { color: seagreen; } }
                h3 { color: dimgray; }

                Choose an answer to see the explanation.

              5. Question 5 of 7What is the specificity of :where(.card .info h3)?

                Choose an answer to see the explanation.

              6. Question 6 of 7tea-card.js and tea-badge.js both import { base } from ./base.js. How many base sheets does the page hold?

                Choose an answer to see the explanation.

              7. Question 7 of 7The page declares @layer state, component, base;. What happens to the layers inside the kit's components?

                Choose an answer to see the explanation.

              Key takeaways

              • Organize a kit's CSS in three tiers: tokens on the page's :root, one base sheet, and one sheet per component.
              • Tokens are custom properties, so they inherit into every shadow root. A component reads them through its own public name: var(--tea-card-accent, var(--tea-color-leaf, seagreen)).
              • The design tokens format, 2025.10, keeps tokens in JSON. A build tool turns them into custom properties.
              • Export the base sheet from one module. A module runs once, so every component adopts the same sheet object, first.
              • Start every sheet with @layer base, component, state;. Then the order holds whichever sheet comes first, and the page's layers can't change it.
              • Keep all of a component's rules in layers. One unlayered rule beats every layer.
              • Keep selectors light: one class or tag, no IDs, and :where() around base rules.

              Remember the one-liner.
              Swatches on :root, one shelving sheet for everyone, a display sheet each, and the same three layers in every shadow root.

              Sources

              The facts on this page come from these standards, docs, posts, and library files:

              Coming next: Motion in components. Components get transitions and animations that respect people who prefer less motion.

              CompleteFrontend Clear concepts. Working examples.