Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Worked example · 25 min · revision 3

Design Tokens and Theming with Custom Properties

Turn raw values into named design tokens, theme the whole product through semantic roles, and keep dark mode and reduced motion to one block each.

Contentsand lesson path

What you will learn

  • Define design tokens (color, spacing, type scale, radius, motion) as CSS custom properties and use them for theming, including dark mode and reduced motion.

Prerequisites: CSS Cascade & Box Model

01. The brief

You inherit a product with an invoice dashboard, a settings area and a sign-up flow. The colours were chosen screen by screen: #1a5ec2 here, #1958ba there, and a blue that only exists in a Figma export. When the brand team asks for dark mode, the answer is an audit of every stylesheet in the product — and when they change the blue to a slightly different blue, the same audit runs again.

Design tokens fix this by giving every raw value a name that describes its job. A token file holds the palette once; components read names like --color-primary and never a hex value. Because a custom property is just a variable that inherits down the tree, re-theming the product means redefining the names at the root — the components do not know it happened.

This worked example builds that token layer for a small dashboard. By the end, a data-theme attribute flips the entire page between light and dark, the operating system's "reduce motion" setting flattens every animation at once, and a script proves the colour pairs still meet the WCAG AA contrast thresholds in both themes.

You need only a browser and a text editor; everything runs as plain files. The two ideas that carry the lesson are palette versus semantic naming, and the fact that custom properties resolve at run time — unlike Sass variables, which are text substitution frozen at build time.

02. Step 1: separate palette from meaning

CSS · tokens.css
/* Palette: raw values. Components never read these. */
:root {
  --gray-0: #ffffff;
  --gray-100: #f2f4f7;
  --gray-300: #c3cad3;
  --gray-600: #4a5560;
  --gray-900: #141a21;
  --brand-100: #dbe9fc;
  --brand-600: #1a5ec2;
  --brand-700: #144a9b;
}

/* Spacing, radius and typography scales */
:root {
  --font-sans: system-ui, -apple-system, sans-serif;
  --text-sm: 0.875rem;
  --text-base: 1rem;
  --text-lg: 1.25rem;
  --space-1: 0.25rem;
  --space-2: 0.5rem;
  --space-4: 1rem;
  --space-6: 1.5rem;
  --radius-sm: 0.25rem;
  --radius-md: 0.5rem;
  --radius-lg: 0.75rem;
}

/* Semantic roles: names describe the job, not the colour. */
:root {
  --color-page: var(--gray-100);
  --color-surface: var(--gray-0);
  --color-ink: var(--gray-900);
  --color-ink-muted: var(--gray-600);
  --color-border: var(--gray-300);
  --color-primary: var(--brand-600);
  --color-on-primary: var(--gray-0);
  --color-primary-soft: var(--brand-100);
  --color-primary-ink: var(--brand-700);
  --color-focus: var(--brand-600);
}

The palette block is the only place a hex value may appear. The semantic block gives each value a role: --color-primary is "the colour that marks the main action", --color-on-primary is "whatever is readable on top of it". Components consume only the semantic names.

The indirection earns its keep twice. A rebrand touches the palette block alone: swap --brand-600 for a green and every primary action in the product follows. A dark theme touches the semantic block alone: the roles stay, the values change. If components read palette names directly, neither change is local any more.

03. Step 2: theme with a data attribute

CSS · tokens.css, continued
:root {
  --slate-700: #33404f;   /* dark palette additions */
  --slate-800: #1c242e;
  --slate-900: #1b2c44;
  --slate-950: #0e1319;
  --sky-200: #aacbf8;
  --sky-300: #8ab9f4;
}

/* Dark theme: same roles, new values. One block. */
[data-theme='dark'] {
  --color-page: var(--slate-950);
  --color-surface: var(--slate-800);
  --color-ink: var(--sky-200);
  --color-ink-muted: var(--sky-300);
  --color-border: var(--slate-700);
  --color-primary: var(--sky-300);
  --color-on-primary: var(--slate-950);
  --color-primary-soft: var(--slate-900);
  --color-primary-ink: var(--sky-200);
  --color-focus: var(--sky-200);
}

The dark block sits on [data-theme='dark'], an attribute on <html>. Custom properties inherit: every element under that attribute resolves --color-surface to the dark value, and every component reading it follows without a single change. Writing the theme as an attribute rather than a media query has three practical payoffs: the reader can choose a side and the choice survives reloads (a media query cannot be stored), a theme toggle is one dataset write, and you can force a theme in tests or screenshots deterministically.

The only rule is that the attribute must exist before first paint, or readers get a flash of the wrong theme. A tiny inline script in <head> does that. Its try block is there because storage is not always available: some privacy settings and sandboxed frames make localStorage throw, and the page should then fall back to the system preference instead of stopping the script:

HTML · index.html (head, before the stylesheet)
<script>
  // Runs before first paint: no flash of the wrong theme.
  let stored = null;
  try { stored = localStorage.getItem('theme'); } catch { /* storage blocked */ }
  const dark = stored
    ? stored === 'dark'
    : matchMedia('(prefers-color-scheme: dark)').matches;
  document.documentElement.dataset.theme = dark ? 'dark' : 'light';
</script>
JavaScript · theme-toggle.js
const root = document.documentElement;
const button = document.querySelector('[data-theme-toggle]');
// Storage can be blocked (privacy settings, sandboxed frames): fail soft.
const savedTheme = () => {
  try { return localStorage.getItem('theme'); } catch { return null; }
};

button.addEventListener('click', () => {
  const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
  root.dataset.theme = next;
  try { localStorage.setItem('theme', next); } catch { /* this visit only */ }
});

// Follow the system preference while the reader has not chosen.
matchMedia('(prefers-color-scheme: dark)').addEventListener('change',
  (event) => {
    if (!savedTheme()) {
      root.dataset.theme = event.matches ? 'dark' : 'light';
    }
  });

04. Step 3: motion tokens and reduced motion

CSS · tokens.css, finished
:root {
  --motion-fast: 150ms;
  --motion-ease: ease-out;
}

@media (prefers-reduced-motion: reduce) {
  :root {
    --motion-fast: 0ms;
  }
}

Durations belong in the token file for the same reason colours do: one name, one value, changed in one place. The button styles its transition as transition: background var(--motion-fast) var(--motion-ease), and the media query above flattens every transition in the product for readers whose operating system asks for reduced motion. No component writes a media query; the token is the integration point. This is the same pattern you met in the CSS foundations lesson for prefers-reduced-motion, now applied at system scale.

05. Step 4: prove the theme works

Claims about styling are cheap; the files below check them in a real Chromium. Save the three CSS blocks above, in order, as tokens.css and the toggle as theme-toggle.js. Next to them goes a complete page: the boot script from step 2, the token file, and one button styled only through semantic tokens.

HTML · index.html (the complete page)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Token demo</title>
  <script>
    // Runs before first paint: no flash of the wrong theme.
    let stored = null;
    try { stored = localStorage.getItem('theme'); } catch { /* blocked */ }
    const dark = stored
      ? stored === 'dark'
      : matchMedia('(prefers-color-scheme: dark)').matches;
    document.documentElement.dataset.theme = dark ? 'dark' : 'light';
  </script>
  <link rel="stylesheet" href="tokens.css">
  <style>
    body { background: var(--color-page); color: var(--color-ink);
           font-family: var(--font-sans); }
    .button { background: var(--color-primary); color: var(--color-on-primary);
              border: 0; border-radius: var(--radius-md);
              padding: var(--space-2) var(--space-4);
              transition: background var(--motion-fast) var(--motion-ease); }
  </style>
</head>
<body>
  <button class="button" type="button" data-theme-toggle>Switch theme</button>
  <script src="theme-toggle.js"></script>
</body>
</html>

The check loads that page from disk, reads computed styles before and after a click on the toggle, emulates the reduced-motion setting, and reloads to confirm the choice was stored. Set the folder up once with npm init -y, npm pkg set type=module, npm install -D [email protected] and npx playwright install chromium. Playwright 1.64 drives the browser here; any recent version works the same way.

JavaScript · verify.mjs
import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(pathToFileURL('index.html').href);

const read = () => page.evaluate(() => {
  const body = getComputedStyle(document.body);
  const button = getComputedStyle(document.querySelector('[data-theme-toggle]'));
  return {
    theme: document.documentElement.dataset.theme,
    body: `${body.backgroundColor} / ${body.color}`,
    button: `${button.backgroundColor} / ${button.color}`,
    // transitionDuration reads "0.15s"; print it in whole milliseconds
    transition: `${Math.round(parseFloat(button.transitionDuration) * 1000)} ms`,
  };
});
const print = (label, s) => console.log(`${label}: theme=${s.theme}\n` +
  `  body        ${s.body}\n  button      ${s.button}\n  transition  ${s.transition}`);

print('light (default)', await read());
await page.click('[data-theme-toggle]');
await page.waitForTimeout(300);            // let the 150 ms transition finish
print('after toggle', await read());
await page.emulateMedia({ reducedMotion: 'reduce' });
console.log('reduced motion transition:', (await read()).transition);
await page.reload();
console.log('after reload, theme kept:', (await read()).theme);
await browser.close();
Expected output · node verify.mjs
light (default): theme=light
  body        rgb(242, 244, 247) / rgb(20, 26, 33)
  button      rgb(26, 94, 194) / rgb(255, 255, 255)
  transition  150 ms
after toggle: theme=dark
  body        rgb(14, 19, 25) / rgb(170, 203, 248)
  button      rgb(138, 185, 244) / rgb(14, 19, 25)
  transition  150 ms
reduced motion transition: 0 ms
after reload, theme kept: dark

Read the numbers as RGB. The button's background rgb(26, 94, 194) in light becomes rgb(138, 185, 244) in dark — that is --color-primary resolving through the new theme, with the text flipping to near-black to stay readable on the lighter blue. The transition still reads 150 ms after the toggle (the computed transition-duration is the string 0.15s, which the script converts) but drops to 0 ms under emulateMedia({ reducedMotion: 'reduce' }), and the stored choice survives a reload. No component stylesheet participated in any of it.

JavaScript · contrast.mjs (WCAG 2.2 relative luminance)
function luminance([r, g, b]) {
  const channel = (value) => {
    const s = value / 255;
    return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
  };
  return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
}

function contrast(hexA, hexB) {
  const parse = (hex) => hex.match(/[0-9a-f]{2}/gi).map((h) => parseInt(h, 16));
  const [hi, lo] = [luminance(parse(hexA)), luminance(parse(hexB))]
    .sort((a, b) => b - a);
  return (hi + 0.05) / (lo + 0.05);
}

const pairs = [
  ['ink on surface', '#141a21', '#ffffff'],
  ['ink-muted on surface', '#4a5560', '#ffffff'],
  ['on-primary on primary', '#ffffff', '#1a5ec2'],
  ['primary-ink on primary-soft', '#144a9b', '#dbe9fc'],
  ['dark ink on surface', '#aacbf8', '#1c242e'],
  ['dark ink-muted on surface', '#8ab9f4', '#1c242e'],
  ['dark on-primary on primary', '#0e1319', '#8ab9f4'],
];
for (const [name, a, b] of pairs) {
  console.log(`${name.padEnd(30)} ${contrast(a, b).toFixed(2)}:1  AA normal text`);
}
Expected output · node contrast.mjs
ink on surface                 17.51:1  AA normal text
ink-muted on surface           7.61:1  AA normal text
on-primary on primary          6.13:1  AA normal text
primary-ink on primary-soft    6.88:1  AA normal text
dark ink on surface            9.40:1  AA normal text
dark ink-muted on surface      7.70:1  AA normal text
dark on-primary on primary     9.17:1  AA normal text

Under WCAG 2.2 AA (the same success criteria as in 2.1), SC 1.4.3 requires 4.5:1 for normal text and 3:1 for large text (at least 24px, or 18.66px bold, corresponding to 14pt bold). Separately, SC 1.4.11 requires 3:1 non-text contrast for user interface components and graphical objects. Every text pair the page actually renders passes with room to spare — checked for both themes at the same time, before anything ships. A token file whose pairs have never been measured is a guess with good marketing.

06. Ways this goes wrong

07. Check your understanding

Practice check · 3 questions

Tokens in practice

Three decisions from the token file you just built.

Q1. The brand team replaces the blue with green. With the two-layer token file from this lesson, where does the change land?
Q2. The button label is 14px regular text on --color-primary. Which minimum contrast ratio does WCAG 2.2 AA require for that pair?
Q3. A stylesheet far from the token file writes `color: var(--color-danger, #a4231b)`. When does the fallback value apply?
Practice only: not graded, not saved, not evidence.

08. Apply it

This is the groundwork for the skill's practice task, the component kit you build in the lab later in this skill.

  1. Take a stylesheet you own and list every raw value: colours, spacing, radii, durations. Sort them into a palette scale and semantic roles, and write the two blocks.
  2. Add a dark block for the semantic roles and a prefers-reduced-motion override for the motion tokens. Run the contrast script over every foreground/background pair in both themes.
  3. Delete one hard-coded value from a component and replace it with a token; then grep your project for remaining hex values outside the token file. The earlier this count reaches zero, the cheaper every theme after it becomes.

09. Review prompt

Without looking back: why do palette names belong to one block and role names to another? What does putting the dark theme on a data attribute (instead of a media query) let you do that a media query cannot? And why does one @media (prefers-reduced-motion) block at the root fix every transition in the product?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check