What you'll learn: By the end of this lesson you will be able to define a design token, organise tokens into primitive, semantic and component tiers, resolve aliases and catch circular or missing ones, turn tokens into CSS custom properties, theme an interface with overrides,
prefers-color-scheme,color-schemeandlight-dark(), check the contrast of every theme in a test, and explain why a nested theme scope can leave a component token on the old value.
Think of a paint chart. A decorator writes "living room wall: Soft Cream" on the plan, not the pigment recipe. If the shop changes what Soft Cream means, every room that uses the name changes with it. And if the plan said "wall: the colour that looks nice", nobody could repaint anything. Design tokens are the names on that plan: the same idea of changing a decision in one place, with the checks that make the change safe.
The running example is the ShopStream storefront, the front end of the grocery marketplace in this course. It needs a light theme, a dark theme and a primary button that stays readable in both. The prerequisite lessons are Design Systems and Accessibility (why the shared layer matters) and Modern CSS Layout and Responsive Design.
The core idea
- A token is a named design decision, such as a colour, a size or a duration, stored as data rather than copied into components.
- Tokens come in tiers. Primitives say what values exist, semantic tokens say what a value is for, and component tokens say how one component uses it. Themes change the middle tier.
- A theme is a set of overrides, and it must be checked. A dark theme is not an inverted light theme: each colour pair has to be checked for contrast on its own, in every theme.
What a token is
The Design Tokens Community Group publishes a format for exchanging tokens between design tools and code. At the time of writing it is a Draft Community Group Report (version 2025.10), not a W3C Standard, and it warns against treating that version as authoritative. This lesson uses its shape because tools read it, not as a ruling. In that shape:
- A token is an object with a
$value.$typenames its type and may be set on the token or inherited from a parent group; tools must not guess a type from the value. - A group is an object with no
$value. Names cannot start with$or contain{,}or.. - A value written as
{group.token}is an alias to another token. - References must not be circular: a tool must detect that and report an error affecting every token in the chain.
Illustration 1: the minimal example
Three tokens and an alias. The lab uses plain hex strings for colours to keep the focus on aliases; the draft's colour type is an object with a colour space and components.
{
"color": {
"$type": "color",
"gray": { "900": { "$value": "#111827" } },
"text": { "default": { "$value": "{color.gray.900}" } }
},
"space": { "$type": "dimension", "4": { "$value": "16px" } }
}
color.text.default resolves to #111827 by following one alias. The lab's resolver reports, for each token, the chain it followed. Section 1 of its demo prints, among others:
button.primary.bg = #2563eb via color.action.primary.bg -> color.blue.600
button.primary.padInline = 16px via space.4
Three tiers
| Tier | Answers | Example | Who may use it |
|---|---|---|---|
| Primitive | What values exist? | color.blue.600 = #2563eb |
Only other tokens |
| Semantic | What is this value for? | color.action.primary.bg = {color.blue.600} |
Components and product code |
| Component | How does one component use it? | button.primary.bg = {color.action.primary.bg} |
That component |
The tiers are a convention, not a rule of the format. A component says what it means ("primary action background") instead of what it looks like ("blue"), and a theme can re-point the semantic tier at other primitives without touching a component.
Figure 1. Aliases across the tiers
How to read this: arrows point at the token being referenced. The accent box is where a theme acts.
A second tool is the blast radius: before changing a token, list everything that reaches it through aliases. The lab's dependentsOf does this. Its section 4 shows the point of the middle tier:
=== 4. Blast radius of changing one token
color.blue.600 -> button.primary.bg, button.primary.focusRing, color.action.primary.bg, color.border.focus
color.action.primary.bg -> button.primary.bg
space.4 -> button.primary.padInline
Changing the blue primitive touches four tokens; changing the semantic action colour touches one.
From tokens to CSS custom properties
On the web, tokens usually become CSS custom properties, one per token: color.text.default becomes --color-text-default. MDN states the rules that matter here:
- A property declared with two dashes is subject to the cascade and inherits from its parent.
- Names are case sensitive:
--my-colorand--My-colorare different properties. var(--name, fallback)uses the fallback when the referenced property is invalid. MDN is explicit that fallbacks are not a way to fix compatibility problems for browsers that lack custom properties.- A value is parsed as valid almost regardless of content, because the browser does not know where it will be used. An invalid substitution is only found when it is used; the property then takes its initial or inherited value.
@propertylets you register a type, an initial value and whether it inherits.
Two different token paths can map to one property name (card.border-width and card-border.width both become --card-border-width). The lab's findNameCollisions catches that; its section 5 ends with:
custom property name clashes: --card-border-width <- card-border.width and card.border-width
Component tokens can be written as literals or as var() references to the semantic property. The lab emits both. Writing references is what lets a theme override only the semantic tier: the dark block has 8 declarations in var() mode against 10 in literal mode, because literal mode must repeat every component token whose final value changed.
Theming: four mechanisms
| Mechanism | How it works | Notes |
|---|---|---|
| Override block | [data-theme="dark"] redeclares the semantic properties |
You choose when it applies: a toggle, a setting, a user choice |
prefers-color-scheme |
A media query reads the user's OS or browser light or dark setting | MDN: widely available since January 2020; light also covers "no preference" |
color-scheme |
Declares which schemes the element supports so the browser adjusts its own UI | Affects the canvas, scrollbars and form controls; for the rest of the page you still choose colours |
light-dark(a, b) |
One declaration that returns the first colour in a light scheme and the second in a dark one | Needs color-scheme: light dark; MDN: widely available since May 2024 |
MDN says color-scheme: light dark on :root opts the page into the user's preference, and that adding <meta name="color-scheme" content="light dark"> before any CSS helps prevent a flash of the wrong scheme while the page loads. light-dark() takes two arguments of the same kind (two colours, or two images), and either can be a var().
These combine. A common arrangement is a stored user choice (light, dark or "system"), applied as an attribute on the root element, with the prefers-color-scheme query deciding when the choice is "system". Browser Storage Options covers where the choice can be saved, and the stored value must be applied before first paint or a returning user sees a flash.
Figure 2. Which theme applies
light or dark?"} A -->|"yes"| B["Set data-theme on the root
(before first paint)"] A -->|"no, system"| C{"prefers-color-scheme
is dark?"} C -->|"yes"| D["Dark overrides
via media query"] C -->|"no"| E["Light base values"] B --> F["Forced colours still
replaces author colours"] D --> F E --> F
How to read this: an explicit choice beats the system setting, and the system setting beats the default. In forced colours mode MDN says the browser overrides author colour properties whatever the theme.
Contrast per theme
A dark theme does not inherit a light theme's contrast. A grey that passes on white can fail on near-black. WCAG defines contrast ratio as (L1 + 0.05) / (L2 + 0.05), where L1 and L2 are the relative luminance of the lighter and the darker colour, with a range of 1 to 21. Relative luminance for sRGB is 0.2126 R + 0.7152 G + 0.0722 B after each 8-bit channel is divided by 255 and linearised (divide by 12.92 up to 0.04045, otherwise ((c + 0.055) / 1.055) ^ 2.4). WCAG 1.4.3 asks for 4.5:1 for normal text and 3:1 for large text; 1.4.11 asks for 3:1 for the parts of a control and its states, such as a focus ring. Computed values must not be rounded.
This is arithmetic, so it can be a test. The lab lists the pairs that matter (body, muted and error text, the primary button label, the focus ring) and checks each in each theme.
Build it
Goal. Resolve the storefront tokens, apply a dark theme, check the pairs, emit CSS, and model how custom properties are computed down nested scopes.
Setup. The lab is examples/frontend/labs/design-tokens-theming in the course workspace. It is a pure TypeScript model: no browser, no DOM, no network. Colours are illustrative values made up for the lab.
cd examples/frontend/labs/design-tokens-theming
../../node_modules/.bin/vitest run
node src/demo.ts
Verified. 44 tests passed (Vitest 5.1.0 on Node 26.13.1, 2026-12-01) across three test files: alias resolution and error reports, contrast, theme overrides, CSS emission and the custom property model. The demo output below is from node src/demo.ts; it was captured twice and the runs were identical.
Step 1: a broken token file is reported. A circular alias, a missing target, a type mismatch, a bad name and a token with no type, in one file:
Expected output, captured from a real run (Node 26.13.1, section 2):
=== 2. A broken token file is reported, not guessed at
bad-name color.bad.name name "bad.name" contains { } or .
circular color.brand circular alias: color.brand -> color.brand-dark -> color.brand
circular color.brand-dark circular alias: color.brand -> color.brand-dark -> color.brand
missing-reference color.accent {color.missing} does not exist
type-mismatch space.gutter declared dimension but {color.ok} is color
unresolved-dependency space.inset {color.accent} could not be resolved
no-type loose no $type on the token or any parent group
Both members of the circular chain are reported, which is what the draft asks of a tool. space.inset is reported separately because it fails only through its dependency. The type check and the "alias takes its target's type" rule are the lab's own simplifications, not claims about the draft.
Step 2: contrast in the dark theme.
Expected output, captured from a real run (Node 26.13.1, section 3, dark theme):
-- dark
pass body text on page 16.98 : 1 (needs 4.5)
FAIL muted text on page 3.67 : 1 (needs 4.5)
FAIL muted text on raised card 3.04 : 1 (needs 4.5)
pass primary button label 6.98 : 1 (needs 4.5)
pass error text on page 6.41 : 1 (needs 4.5)
pass focus ring on page 6.98 : 1 (needs 3)
The dark theme leaves color.text.muted pointing at the same grey as the light theme. That grey reaches 4.83:1 on the light page and 3.67:1 on the dark one. The test "fails exactly the two muted-text pairs in the dark theme" keeps this visible, and a real build would fail it.
Step 3: the CSS.
Expected output, captured from a real run (Node 26.13.1, section 5, the dark block in var() mode and the counts):
dark block, literal mode: 10 declarations
dark block, var mode: 8 declarations
:root {
--button-primary-bg: var(--color-action-primary-bg);
--button-primary-text: var(--color-action-primary-text);
--color-action-primary-bg: var(--color-blue-600);
--color-action-primary-text: var(--color-gray-0);
}
[data-theme="dark"] {
--color-action-primary-bg: var(--color-blue-400);
--color-action-primary-text: var(--color-gray-900);
--color-border-focus: var(--color-blue-400);
--color-danger-text: var(--color-red-400);
--color-surface-default: var(--color-gray-900);
--color-surface-raised: var(--color-gray-800);
--color-text-default: var(--color-gray-50);
--color-text-muted: var(--color-gray-500);
}
The :root block in the demo is filtered to four lines for readability; the dark block is complete. Note that the dark block overrides only semantic properties. The button tokens follow through var().
The failure: a theme scope below the root
Custom properties that use var() are substituted where they are declared, not where they are used. The CSS Custom Properties specification says custom properties resolve their var() functions at computed-value time, and that an element inherits the value after substitution. So a component token declared on :root as var(--semantic) is computed on :root, and every descendant inherits that computed value.
That is fine while the theme attribute sits on the root element, because the override and the component token are declared on the same element. It breaks when a theme is applied to a subtree, for example a dark panel inside a light page:
Figure 3. Nested theme scope
How to read this: the component property was substituted once, on the root. Overriding the semantic property lower down does not re-run that substitution for an inherited value; the scope has to declare the component property again.
The lab's computeAt models just these rules. Section 6 of the demo:
Expected output, captured from a real run (Node 26.13.1, section 6):
=== 6. A theme scope below the root: what the button inside it gets
root only --button-primary-bg = #2563eb
dark scope sets the semantic token --button-primary-bg = #2563eb
dark scope sets it and the button --button-primary-bg = #60a5fa
cycle: --a = invalid, --b = invalid, --c = red
The third line is the fix: write the dependent component tokens again in the theme block (the lab's themeBlock has a redeclareDependents option for this). The last line shows that every property in a cycle is invalid, as the specification says, and that a fallback applies to a reference into the cycle. This is the lab's own model of the specification's rules, not a browser, so test your own nested themes in a browser before relying on it.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Three tiers | Themes change one tier; components stay meaning-based | More names to maintain and document |
var() references for component tokens |
Small theme blocks | Nested theme scopes must redeclare dependents |
| Literal values for component tokens | A scope always sees the right value | Larger output; every dependent repeated per theme |
light-dark() |
Light and dark values side by side | Only colours and images; needs color-scheme; no third theme |
| Contrast check in the build | A theme cannot ship with a failing pair | Pairs must be listed and kept current |
In practice: adding a dark theme to the storefront
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The storefront ships with hard-coded hex values in about two hundred style rules. Marketing wants a dark theme and the admin app wants to reuse the palette. A first attempt copies the stylesheet and inverts colours by hand; review finds low-contrast muted text and a button whose label disappears.
Starting architecture
Figure 4. Colours copied into rules
How to read this: the warning boxes are where colour decisions are duplicated. Any change must be made twice, and nothing checks that a pair is readable.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Hand-edit a second stylesheet | Fast | Two sources of truth | Drift and unchecked pairs |
| Tokens with an override block | One source; the dark theme is a short list | Migrating rules to var() |
Nested scopes (above) |
The decision
| Field | Decision record |
|---|---|
| Context | Hard-coded colours block a second theme and shared palette. |
| Decision | Define primitive, semantic and component tokens as data; emit custom properties; write the dark theme as overrides of the semantic tier on the root element; add a build test that checks each listed pair in each theme; set color-scheme and the meta tag. |
| Consequences, good | One list of decisions for both apps; a failing pair stops the build; a rebrand changes primitives. |
| Consequences, bad | Token names become an API that product teams depend on; the pair list needs upkeep. |
| Revisit when | A theme is needed inside a subtree, a high-contrast theme is requested, or a token tool replaces the build step. |
Rollout and verification
- Resolve the tokens in a test and fail on any problem: missing, circular, type mismatch, name clash.
- List the colour pairs and fail the build when a theme misses its minimum.
- Migrate rules in slices, replacing hex with
var()references. - Apply the stored choice before first paint and set
color-schemeand the meta tag. - Check by eye in both themes and in forced colours: arithmetic proves a ratio, not legibility.
The 2 a.m. failure
A promotion banner is added inside a dark panel on a light page. Its button keeps the light theme's colours: the label is white on a pale blue, unreadable. The banner's theme block overrides the semantic tokens, but the button's component tokens were declared on the root as var() references and inherited as already computed values.
First three checks: (1) in developer tools, read the computed value of the component property on the button and on the panel; (2) compare with the semantic property on the same element; (3) look for a theme block that lists only semantic tokens. Mitigation: redeclare the dependent component tokens in the panel's theme block. Follow-up: emit dependents for nested scopes by default and add a test for a nested theme.
Architect's notes
- Name tokens for meaning (
color.action.primary.bg), and let only the semantic tier reach components. - Treat token names as a public API. Renaming is a breaking change for every product.
- Test the data, not the paint. Resolution, name clashes and contrast ratios are checkable without a browser.
Common mistakes
- Components that use primitives directly, so a theme cannot change them.
- A dark theme that is an inverted light theme, or a contrast ratio rounded before comparison.
- Using
var()fallbacks as a browser-compatibility fix. - Setting the theme after first paint, which flashes the wrong theme.
- Component tokens declared only on the root when themes apply to subtrees.
Key takeaways
- A token is a named decision; an alias references another token, and circular aliases are errors.
- Three tiers (primitive, semantic, component) let a theme change one tier.
- Tokens become CSS custom properties;
var()is substituted at computed-value time and inherited as a computed value. prefers-color-scheme,color-scheme,light-dark()and an override attribute solve different parts of theming and combine.- Check every colour pair in every theme with the WCAG formula, without rounding.
- A nested theme scope must redeclare dependent component tokens, or they keep the old value.
Practice exercises
Exercise 1: Starter (30 min). Add a color.text.inverse semantic token to the lab's storefront set and a button label that uses it. Run the tests and the demo.
Exercise 2: Intermediate (2 hours). Fix the dark theme's muted text by choosing a lighter primitive. Add a test that every pair passes in both themes, and find the smallest change that does it.
Exercise 3: Advanced (half day). Extend the lab with a "high contrast" theme and a stricter minimum for text. Emit its block in both modes and add a nested-scope test that fails if dependents are not redeclared.
Related reading
In this course:
- CSS Architecture and Scaling: custom properties and a
tokenscascade layer. - Modern CSS Layout and Responsive Design: spacing and size tokens in layout.
- Browser Storage Options: where a theme choice can be stored.
- Component-Based Architecture: the components that consume tokens.
- Monorepos and Shared Libraries: sharing a token package between apps.
Official documentation
- Design Tokens Community Group: Format Module (draft): tokens, groups, aliases, circular references.
- W3C: CSS Custom Properties for Cascading Variables Level 1: computed-value time and cycles.
- MDN: Using CSS custom properties: inheritance, fallbacks,
@property. - MDN: color-scheme, light-dark() and prefers-color-scheme.
- W3C: Understanding SC 1.4.3 Contrast (Minimum) and SC 1.4.11 Non-text Contrast.
- W3C: WCAG 2.2 relative luminance.