Skip to main content

Frontend development · Intermediate · 24 min

Build a living style guide page from CSS tokens

By Padding · Updated 18 Nov 2026
Modern browsers · CSS Custom Properties Level 1 and CSSOM · checked in Chromium 159 · Node.js 26 · Playwright 1.65.1

You will have a style guide page that reads every token from tokens.css when it loads and shows the palette with contrast ratios, the type scale, the spacing scale and the Larkfield components in their states, plus a Playwright test that fails when a token is missing.

On this page

A style guide written by hand starts going stale the day after it is published. Someone changes a token in the stylesheet, nobody updates the document, and six months later the guide shows a teal that no screen uses. Larkfield Clinic's design team keeps a written guide in Figma for the decisions and the reasons. The developers want a second page next to the code that cannot drift, because it has no values of its own.

That is what you build here: one HTML page that, every time it loads, reads the custom properties declared in tokens.css through the browser's CSS Object Model (CSSOM) and draws them. It shows each colour with the contrast ratio of the pairs the app really uses, each step of the type scale, each spacing and radius value, and the booking app's components in their states, styled by the real components.css. Add a token and it appears. Change one and the page shows the new value. Delete one that a component needs, and the page and a Playwright test both say which one.

You will use the Larkfield tokens from Turn design tokens into CSS custom properties, with type tokens added. You do not need to have done that tutorial; this one gives you the files.

Step 1 · Set up the tokens and components

Make a demo folder with the two stylesheets the guide will read. tokens.css holds three groups of primitives (colours, spacing and type) and a semantic layer that points at them. Components use only the semantic layer:

Bash
mkdir -p ~/styleguide-demo
cd ~/styleguide-demo
cat > tokens.css <<'CSS'
/* Layer 1: primitives. Raw values, named family-step. */
:root {
  --grey-0: #ffffff;
  --grey-50: #f6f7f8;
  --grey-200: #d5d9df;
  --grey-500: #7d8592;
  --grey-600: #5a6270;
  --grey-900: #1b1f24;
  --teal-50: #e3f0ee;
  --teal-700: #0f5e5a;
  --red-50: #fdecea;
  --red-700: #b42318;
  --amber-50: #fff4dc;
  --amber-700: #8a5a00;

  --space-4: 0.25rem;
  --space-8: 0.5rem;
  --space-12: 0.75rem;
  --space-16: 1rem;
  --space-24: 1.5rem;
  --space-32: 2rem;
  --radius-8: 0.5rem;
}

/* Layer 2: semantic tokens. Named for a job; components use only these. */
:root {
  --colour-text: var(--grey-900);
  --colour-text-muted: var(--grey-600);
  --colour-surface: var(--grey-0);
  --colour-canvas: var(--grey-50);
  --colour-line: var(--grey-200);
  --colour-border: var(--grey-500);
  --colour-accent: var(--teal-700);
  --colour-accent-tint: var(--teal-50);
  --colour-on-accent: var(--grey-0);
  --colour-danger: var(--red-700);
  --colour-danger-tint: var(--red-50);
  --colour-notice: var(--amber-700);
  --colour-notice-tint: var(--amber-50);

  --space-stack-s: var(--space-8);
  --space-stack-m: var(--space-16);
  --space-stack-l: var(--space-24);
  --space-stack-xl: var(--space-32);
  --space-inset-screen: var(--space-16);
  --space-inset-control: var(--space-12);
  --radius-control: var(--radius-8);
}

/* Type scale: one size and one line height per role. */
:root {
  --type-heading-l-size: 1.5625rem;
  --type-heading-l-line-height: 2rem;
  --type-heading-m-size: 1.25rem;
  --type-heading-m-line-height: 1.5rem;
  --type-body-size: 1rem;
  --type-body-line-height: 1.5rem;
  --type-body-small-size: 0.875rem;
  --type-body-small-line-height: 1.25rem;
}
CSS

Now the components. These are a few pieces of the booking app in every state the guide needs to show: time slots (free, selected, unavailable), the two buttons (and a Continue that is not available yet), a keyboard focus ring, the notice from Pick a time, the Booked banner and the error message from Your details:

Bash
cd ~/styleguide-demo
cat > components.css <<'CSS'
.slot,
.button-primary,
.button-secondary {
  min-height: 48px;
  padding: 0 var(--space-inset-control);
  font: inherit;
  border-radius: var(--radius-control);
}

.slot {
  background: var(--colour-surface);
  color: var(--colour-text);
  border: 1px solid var(--colour-border);
}
.slot[aria-pressed="true"] {
  background: var(--colour-accent);
  color: var(--colour-on-accent);
  border-color: var(--colour-accent);
}
.slot:disabled {
  background: var(--colour-canvas);
  color: var(--colour-text-muted);
  border-color: var(--colour-line);
  text-decoration: line-through;
}

.button-primary {
  font-weight: 600;
  background: var(--colour-accent);
  color: var(--colour-on-accent);
  border: 1px solid var(--colour-accent);
}
.button-secondary {
  font-weight: 600;
  background: var(--colour-surface);
  color: var(--colour-accent);
  border: 1px solid var(--colour-border);
}
.button-primary[aria-disabled="true"] {
  background: var(--colour-line);
  color: var(--colour-text-muted);
  border-color: var(--colour-line);
}

.slot:focus-visible,
.button-primary:focus-visible,
.button-secondary:focus-visible {
  outline: 2px solid var(--colour-accent);
  outline-offset: 2px;
}

.notice,
.banner,
.error {
  margin: 0;
  padding: var(--space-inset-control);
  border-radius: var(--radius-control);
}
.notice { background: var(--colour-notice-tint); color: var(--colour-notice); }
.banner { background: var(--colour-accent-tint); color: var(--colour-text); }
.error {
  background: var(--colour-danger-tint);
  color: var(--colour-danger);
  border: 1px solid var(--colour-danger);
}
CSS

The unavailable slot is struck through as well as greyed out, so it does not rely on colour alone to say "you cannot pick this". The unavailable Continue uses aria-disabled="true" rather than the disabled attribute, as in Build the Larkfield button in HTML and CSS: it stays in the Tab order and is announced with its reason. The focus ring uses the accent colour, which is what that tutorial's --colour-focus points at.

Check it worked

Run grep -c -- '^ --' tokens.css. It prints 47: nineteen primitives, twenty semantic tokens and eight type tokens. Run grep -o 'var(--[a-z0-9-]*' components.css | sort -u | wc -l and it prints 15, the number of different tokens the components use.

Step 2 · Serve the folder and write the page shell

The guide reads the rules inside tokens.css with JavaScript. Chromium and Firefox do not let a page opened straight from disk (a file:// address) read the rules of its stylesheets: they throw a security error, because every local file counts as a separate origin. So the page needs a small web server. Node has one built in. Save this as serve.mjs:

Bash
cd ~/styleguide-demo
cat > serve.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join, normalize, sep } from 'node:path';
import { fileURLToPath } from 'node:url';

const dir = fileURLToPath(new URL('.', import.meta.url));
const types = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript' };
export const port = Number(process.env.PORT ?? 8123);

export const server = createServer(async (req, res) => {
  const path = new URL(req.url, 'http://localhost').pathname;
  const file = normalize(join(dir, path === '/' ? 'styleguide.html' : path));
  const type = types[extname(file)];
  if (!file.startsWith(dir.endsWith(sep) ? dir : dir + sep) || !type) {
    res.writeHead(404).end('Not found');
    return;
  }
  try {
    res.writeHead(200, { 'content-type': type }).end(await readFile(file));
  } catch {
    res.writeHead(404).end('Not found');
  }
});

server.listen(port, '127.0.0.1', () => {
  console.log(`Style guide at http://127.0.0.1:${port}/`);
});
JS

It serves only HTML, CSS and JavaScript from this folder, and only to your own machine (127.0.0.1). The port comes from the PORT environment variable, or 8123 if it is not set; the test in a later step uses that to run its own copy on another port.

Now the page. Every section except Components is an empty element that the script fills. The Components section is ordinary HTML that uses the real component classes, so it always shows what components.css does today:

Bash
cd ~/styleguide-demo
cat > styleguide.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Larkfield style guide</title>
  <link rel="stylesheet" href="tokens.css">
  <link rel="stylesheet" href="components.css">
  <link rel="stylesheet" href="guide.css">
  <script src="styleguide.js" defer></script>
</head>
<body>
  <main class="guide">
    <header>
      <h1>Larkfield style guide</h1>
      <p class="muted">Drawn from tokens.css each time this page loads.</p>
      <p id="guide-status" role="status">Reading tokens…</p>
    </header>

    <section aria-labelledby="colour-heading">
      <h2 id="colour-heading">Colour</h2>
      <h3>Semantic colours</h3>
      <div id="semantic-colours" class="swatches"></div>
      <h3>Primitives</h3>
      <div id="primitive-colours" class="swatches"></div>
      <h3>Contrast of the pairs the app uses</h3>
      <div class="table-wrap">
        <table id="contrast">
          <thead><tr><th scope="col">Pair</th><th scope="col">Ratio</th><th scope="col">Needs</th><th scope="col">Result</th></tr></thead>
          <tbody></tbody>
        </table>
      </div>
    </section>

    <section aria-labelledby="type-heading">
      <h2 id="type-heading">Type</h2>
      <div id="type-scale"></div>
    </section>

    <section aria-labelledby="space-heading">
      <h2 id="space-heading">Spacing and radius</h2>
      <div id="spacing"></div>
      <div id="radius"></div>
    </section>

    <section aria-labelledby="components-heading">
      <h2 id="components-heading">Components</h2>
      <h3>Time slot</h3>
      <div class="specimen">
        <button class="slot" type="button" aria-pressed="false">09:30</button>
        <button class="slot" type="button" aria-pressed="true">10:30</button>
        <button class="slot" type="button" disabled>11:00</button>
      </div>
      <p class="muted">Free, selected, unavailable.</p>
      <h3>Buttons</h3>
      <div class="specimen">
        <button class="button-primary" type="button">Continue</button>
        <button class="button-secondary" type="button">Back</button>
        <button class="button-primary" type="button" aria-disabled="true" aria-describedby="continue-why">Continue</button>
      </div>
      <p class="muted" id="continue-why">Choose a time first.</p>
      <p class="muted">Primary, secondary, primary not available yet. Press Tab to move through the slots and buttons and see the focus ring.</p>
      <h3>Messages</h3>
      <div class="specimen specimen-stack">
        <p class="notice">Only 2 times left this morning</p>
        <p class="banner">Booked: Nurse appointment, Tuesday 9 December, 10:30</p>
        <p class="error">Error: Enter a mobile number with 11 digits, such as 07700 900123</p>
      </div>
    </section>
  </main>
</body>
</html>
HTML

Last, the guide's own layout. It uses the same tokens as the app, so the guide is a small proof that the tokens are enough to build a page:

Bash
cd ~/styleguide-demo
cat > guide.css <<'CSS'
* { box-sizing: border-box; }
body {
  margin: 0;
  font-family: Inter, system-ui, sans-serif;
  font-size: var(--type-body-size);
  line-height: var(--type-body-line-height);
  background: var(--colour-canvas);
  color: var(--colour-text);
}
.guide {
  max-width: 60rem;
  margin: 0 auto;
  padding: var(--space-inset-screen);
  display: grid;
  gap: var(--space-stack-l);
}
section {
  background: var(--colour-surface);
  border: 1px solid var(--colour-line);
  border-radius: var(--radius-control);
  padding: var(--space-inset-screen);
}
h1 { font-size: var(--type-heading-l-size); line-height: var(--type-heading-l-line-height); margin: 0; }
h2 { font-size: var(--type-heading-m-size); line-height: var(--type-heading-m-line-height); margin: 0 0 var(--space-stack-m); }
h3 { font-size: var(--type-body-size); margin: var(--space-stack-l) 0 var(--space-stack-s); }
.muted, figcaption, code, td, th { color: var(--colour-text-muted); font-size: var(--type-body-small-size); line-height: var(--type-body-small-line-height); }
.muted { margin: var(--space-stack-s) 0 0; }
code { font-family: ui-monospace, monospace; overflow-wrap: anywhere; }
#guide-status { font-weight: 600; margin: var(--space-stack-s) 0 0; }
#guide-status[data-ok="false"] { color: var(--colour-danger); }

.swatches { display: grid; grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); gap: var(--space-stack-m); }
.swatches figure { margin: 0; }
.chip { height: 3rem; border: 1px solid var(--colour-line); border-radius: var(--radius-control); }
figcaption { display: grid; margin-top: var(--space-stack-s); }
figcaption strong { color: var(--colour-text); }

.table-wrap { overflow-x: auto; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: var(--space-stack-s); border-bottom: 1px solid var(--colour-line); }
td[data-pass="false"] { color: var(--colour-danger); font-weight: 600; }

.type-row, .space-row { display: grid; gap: var(--space-stack-s); padding: var(--space-stack-s) 0; border-bottom: 1px solid var(--colour-line); }
.type-row p { margin: 0; }
.bar { height: 1rem; background: var(--colour-accent); }
.corner { width: 4rem; height: 4rem; border: 2px solid var(--colour-accent); }

.specimen { display: flex; flex-wrap: wrap; gap: var(--space-stack-s); }
.specimen-stack { flex-direction: column; }
CSS

Check it worked

Start the server:

Bash
node serve.mjs

It prints Style guide at http://127.0.0.1:8123/. Open that address in your browser. You see the heading "Larkfield style guide", the line "Reading tokens…", empty Colour, Type and Spacing sections, and a Components section with three slots (10:30 in teal, 11:00 greyed and struck through), two buttons and a grey Continue that is not available yet, and three coloured message boxes. Press Tab a few times: each slot and button gets a teal ring, the grey Continue included, because aria-disabled keeps it in the Tab order. In the app a script stops that Continue from doing anything until a time is chosen; on this page it is only a specimen. The empty sections are next. Leave the server running in this terminal and use a second terminal for the following steps; press Ctrl+C to stop it when you are done.

Step 3 · Read every token from tokens.css

document.styleSheets lists the stylesheets on the page, and each one's cssRules holds its rules as objects. A rule's style property is a CSSStyleDeclaration, and looping over it gives the property names declared in that rule, custom properties included. That lets the script list every token in the order it was written, with the value as written (var(--teal-700)). getComputedStyle(document.documentElement).getPropertyValue() then gives the value after every var() has been resolved (#0f5e5a).

The same walk over the other stylesheets finds every var(--…) they use. Any name that is used but not declared is a missing token: the browser would ignore that declaration without any error in the console, so the page says it out loud instead.

Bash
cd ~/styleguide-demo
cat > styleguide.js <<'JS'
const root = document.documentElement;
const fileOf = (sheet) => (sheet.href ? new URL(sheet.href).pathname.split('/').pop() : 'inline');
const sheets = [...document.styleSheets];
const tokenSheets = sheets.filter((s) => fileOf(s) === 'tokens.css');

// Every custom property declared on :root in tokens.css, in source order.
const tokens = [];
for (const sheet of tokenSheets) {
  for (const rule of sheet.cssRules) {
    if (rule.selectorText !== ':root') continue;
    for (const name of rule.style) {
      if (name.startsWith('--')) tokens.push({ name, source: rule.style.getPropertyValue(name).trim() });
    }
  }
}
const defined = new Set(tokens.map((t) => t.name));
const resolved = (name) => getComputedStyle(root).getPropertyValue(name).trim();

// Every var(--name) used anywhere else, including inside tokens.css itself.
const uses = [];
const collect = (rules, file) => {
  for (const rule of rules) {
    if (rule.style) {
      for (const [, name] of rule.style.cssText.matchAll(/var\(\s*(--[\w-]+)/g)) uses.push({ name, file });
    }
    if (rule.cssRules) collect(rule.cssRules, file);
  }
};
for (const sheet of sheets) collect(sheet.cssRules, fileOf(sheet));

const missing = new Map();
const need = (name, where) => {
  if (!defined.has(name) && !missing.has(name)) missing.set(name, where);
  return defined.has(name);
};
for (const { name, file } of uses) need(name, file);

const el = (tag, { dataset = {}, ...props } = {}, ...children) => {
  const node = Object.assign(document.createElement(tag), props);
  Object.assign(node.dataset, dataset);
  node.append(...children);
  return node;
};

function report() {
  const status = document.querySelector('#guide-status');
  const list = [...missing].map(([name, where]) => `${name} (${where})`);
  status.textContent = list.length
    ? `${tokens.length} tokens read. Missing: ${list.join(', ')}`
    : `${tokens.length} tokens read. None missing.`;
  status.dataset.ok = String(list.length === 0);
  status.dataset.missing = [...missing.keys()].join(' ');
}
report();
JS

Two details. The script compares selectorText with ':root', so a token declared under any other selector (a dark theme on [data-theme="dark"], say) is not listed as a base token; extend the check when you add themes. And the regular expression finds the first name in each var() and also any var() nested inside a fallback, which is what you want here.

Check it worked

Reload http://127.0.0.1:8123/. The status line under the heading now reads "47 tokens read. None missing." In the browser's Console (F12), run tokens.length and it prints 47; run tokens[25] and it shows {name: '--colour-accent', source: 'var(--teal-700)'}.

Step 4 · Draw the palette with contrast ratios

Colours come in two groups. Semantic colours are the tokens whose names start with --colour-, and the guide shows which primitive each one points at. Primitive colours are any other token whose value the browser accepts as a colour, which CSS.supports('color', value) answers.

For contrast, the guide needs each colour as red, green and blue numbers. A resolved token could be written as a hex code, rgb(), hsl() or a colour name, so the script sets it as the color of a hidden element and reads it back from getComputedStyle, which always reports a simple sRGB colour as rgb(r, g, b). The ratio uses the relative luminance formula from WCAG 2.2.

Which pairs to check is a design decision, not something the script can guess, so it is written down as a list: each foreground token, the background it sits on in the app, and the minimum ratio. Normal text needs 4.5:1. The outline of a control needs 3:1 against what is next to it, because it is how people see where the control is. The disabled button and slot are left out on purpose: WCAG does not set a contrast minimum for controls that are not available, but keep them readable anyway. Append the colour section:

Bash
cd ~/styleguide-demo
cat >> styleguide.js <<'JS'

// Colour: swatches and contrast.
const probe = el('span', { hidden: true });
document.body.append(probe);
const rgbOf = (colour) => {
  probe.style.color = colour;
  return getComputedStyle(probe).color.match(/[\d.]+/g).slice(0, 3).map(Number);
};
const hexOf = (colour) => '#' + rgbOf(colour).map((c) => Math.round(c).toString(16).padStart(2, '0')).join('');
const luminance = (colour) => {
  const [r, g, b] = rgbOf(colour).map((c) => {
    const s = c / 255;
    return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
  });
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
const contrast = (a, b) => {
  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (hi + 0.05) / (lo + 0.05);
};

const swatch = (t) =>
  el('figure', { dataset: { token: t.name } },
    el('div', { className: 'chip', style: `background: var(${t.name})` }),
    el('figcaption', {},
      el('strong', { textContent: t.name }),
      el('code', { textContent: t.source.startsWith('var(') ? `→ ${t.source.slice(4, -1)}` : t.source }),
      el('code', { textContent: hexOf(resolved(t.name)) })));

const isColour = (t) => CSS.supports('color', resolved(t.name));
const semanticColours = tokens.filter((t) => t.name.startsWith('--colour-'));
const primitiveColours = tokens.filter((t) => !t.name.startsWith('--colour-') && !t.source.startsWith('var(') && isColour(t));
document.querySelector('#semantic-colours').append(...semanticColours.map(swatch));
document.querySelector('#primitive-colours').append(...primitiveColours.map(swatch));

const pairs = [
  ['--colour-text', '--colour-surface', 4.5],
  ['--colour-text', '--colour-canvas', 4.5],
  ['--colour-text-muted', '--colour-surface', 4.5],
  ['--colour-text-muted', '--colour-canvas', 4.5],
  ['--colour-accent', '--colour-surface', 4.5],
  ['--colour-on-accent', '--colour-accent', 4.5],
  ['--colour-text', '--colour-accent-tint', 4.5],
  ['--colour-danger', '--colour-danger-tint', 4.5],
  ['--colour-notice', '--colour-notice-tint', 4.5],
  ['--colour-border', '--colour-surface', 3],
];
const rows = [];
for (const [fg, bg, min] of pairs) {
  if (!need(fg, 'contrast pairs') || !need(bg, 'contrast pairs')) continue;
  const ratio = contrast(resolved(fg), resolved(bg));
  const pass = ratio >= min;
  rows.push(el('tr', { dataset: { pair: `${fg} on ${bg}`, ratio: ratio.toFixed(2), pass: String(pass) } },
    el('td', {}, el('code', { textContent: `${fg} on ${bg}` })),
    el('td', { textContent: `${ratio.toFixed(2)}:1` }),
    el('td', { textContent: `${min}:1` }),
    el('td', { textContent: pass ? 'Pass' : 'Fail', dataset: { pass: String(pass) } })));
}
document.querySelector('#contrast tbody').append(...rows);
report();
JS

The ratio is compared before it is rounded, so a pair at 4.496:1 fails even though it would print as 4.50:1. A pair whose token is missing is not drawn; it goes into the missing list instead.

Check it worked

Reload the page. Under Semantic colours you see thirteen swatches, each with its name, the primitive it points at (--colour-accent shows → --teal-700) and a hex code. Under Primitives you see twelve. The contrast table has ten rows, all marked Pass. White on the accent reads 7.58:1, muted text on the canvas 5.73:1 and the control border on white 3.72:1. If you change a token so a pair falls short, its result turns red and reads Fail.

Step 5 · Draw the type scale, spacing and radius

Type tokens come in pairs, --type-<role>-size and --type-<role>-line-height. The script finds each size token, derives the role from the name and draws a sample line in that role, then reads the font size and line height back from the rendered sample in pixels. If a role has a size but no line height, the line height is added to the missing list.

Spacing and radius work the same way: each token draws a bar or a rounded square, and the label shows the measured width in pixels next to the value as written. A semantic spacing token shows the primitive it points at, so you can see that --space-stack-m and --space-inset-screen are both 16 pixels, for different reasons:

Bash
cd ~/styleguide-demo
cat >> styleguide.js <<'JS'

// Type: one sample per role.
const typeRows = [];
for (const t of tokens) {
  const match = t.name.match(/^--type-(.+)-size$/);
  if (!match) continue;
  const role = match[1];
  const lineHeight = `--type-${role}-line-height`;
  if (!need(lineHeight, `type role ${role}`)) continue;
  const sample = el('p', {
    textContent: 'Pick a time for your Nurse appointment',
    style: `font-size: var(${t.name}); line-height: var(${lineHeight})`,
  });
  const label = el('code');
  typeRows.push(el('div', { className: 'type-row', dataset: { role } }, label, sample));
  queueMicrotask(() => {
    const cs = getComputedStyle(sample);
    label.textContent = `${role}: ${cs.fontSize} / ${cs.lineHeight} (${t.source})`;
    sample.dataset.size = cs.fontSize;
  });
}
document.querySelector('#type-scale').append(...typeRows);

// Spacing and radius: draw each value, then measure it.
const measured = (t, shape) => {
  const label = el('code');
  const row = el('div', { className: 'space-row', dataset: { token: t.name } }, label, shape);
  queueMicrotask(() => {
    const px = shape.className === 'bar' ? shape.getBoundingClientRect().width : parseFloat(getComputedStyle(shape).borderTopLeftRadius);
    const via = t.source.startsWith('var(') ? `→ ${t.source.slice(4, -1)}` : t.source;
    label.textContent = `${t.name}: ${px}px (${via})`;
    row.dataset.px = String(px);
  });
  return row;
};
document.querySelector('#spacing').append(
  ...tokens.filter((t) => t.name.startsWith('--space-'))
    .map((t) => measured(t, el('div', { className: 'bar', style: `width: var(${t.name})` }))));
document.querySelector('#radius').append(
  ...tokens.filter((t) => t.name.startsWith('--radius-'))
    .map((t) => measured(t, el('div', { className: 'corner', style: `border-radius: var(${t.name})` }))));
report();
JS

The measurements run in queueMicrotask, after the rows are in the page, because an element that is not yet in the document has no size and no computed style to read.

Check it worked

Reload. The Type section shows four sample lines, largest first, labelled heading-l: 25px / 32px (1.5625rem) down to body-small: 14px / 20px (0.875rem). The Spacing section shows twelve bars: the six primitives from --space-4: 4px (0.25rem) to --space-32: 32px (2rem), then the six semantic ones, such as --space-inset-control: 12px (→ --space-12). Below them are two rounded squares, both 8px. The status line still reads "47 tokens read. None missing."

On a phone the page is a single column and nothing scrolls sideways; only the contrast table scrolls inside its own box if it has to. The page loads no fonts, images or libraries, so it costs very little data to open on a prepaid connection, which matters if the team checks it on their phones.

Step 6 · Change a token and watch the guide follow

This is the property that makes the guide worth having. In tokens.css, change the accent primitive from teal to a darker teal: edit the line --teal-700: #0f5e5a; to read --teal-700: #0b4a47; and save. Reload the guide.

You did not touch the guide's script or its HTML, yet the --teal-700 and --colour-accent swatches show #0b4a47, the white-on-accent row in the contrast table goes up from 7.58:1, the selected 10:30 slot and Continue are darker, and so are the spacing bars, which use the accent too.

Now try a change that should be caught. Point the muted text at the lighter grey: change --colour-text-muted: var(--grey-600); to --colour-text-muted: var(--grey-500); and reload. The two --colour-text-muted rows in the contrast table turn red and read Fail (3.72:1 on white and 3.47:1 on the canvas, under the 4.5:1 that normal text needs). Put both lines back the way they were before you go on.

Check it worked

After putting the lines back, grep -- '--teal-700:' tokens.css prints --teal-700: #0f5e5a; and grep -- '--colour-text-muted:' tokens.css prints --colour-text-muted: var(--grey-600);. The guide shows all ten contrast rows as Pass again.

Step 7 · Write a test that fails when a token is missing

The page tells a person when something is wrong. A test tells your continuous integration (CI) server, so a pull request that deletes a token the components need cannot be merged quietly. Playwright drives a real browser from Node. Install it in the demo folder, pinned to the version this tutorial was checked with, and download its Chromium build. The download is large, so on prepaid mobile data do this on Wi-Fi if you can:

Bash
cd ~/styleguide-demo
npm init -y > /dev/null
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromium

On Linux, --with-deps installs the system libraries Chromium needs and may ask for your password. On macOS and Windows it has nothing extra to install.

The test starts its own copy of the server on port 8124, so it does not clash with the one you may still have running on 8123. It opens the guide and fails if the page throws an error, if any token is missing, if any of the semantic colours in tokens.css has no swatch, or if any contrast pair fails:

Bash
cd ~/styleguide-demo
cat > test-styleguide.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { once } from 'node:events';

process.env.PORT ??= '8124';
const { server, port } = await import('./serve.mjs');
if (!server.listening) await once(server, 'listening');

const browser = await chromium.launch();
try {
  const page = await browser.newPage();
  const errors = [];
  page.on('pageerror', (e) => errors.push(e.message));
  await page.goto(`http://127.0.0.1:${port}/styleguide.html`);
  await page.waitForSelector('#guide-status[data-ok]');

  assert.deepEqual(errors, [], 'the page threw an error');
  const status = await page.textContent('#guide-status');
  const missing = await page.getAttribute('#guide-status', 'data-missing');
  assert.equal(missing, '', status);

  const declared = [...readFileSync(new URL('tokens.css', import.meta.url), 'utf8').matchAll(/^\s*(--colour-[\w-]+)\s*:/gm)].map((m) => m[1]);
  for (const name of declared) {
    assert.equal(await page.locator(`[data-token="${name}"]`).count(), 1, `no swatch for ${name}`);
  }

  const failing = await page.$$eval('#contrast tr[data-pass="false"]', (rows) => rows.map((r) => `${r.dataset.pair} ${r.dataset.ratio}:1`));
  assert.deepEqual(failing, [], 'contrast pairs below their minimum');

  console.log(`PASS: ${status} ${declared.length} semantic colours, all contrast pairs pass.`);
} finally {
  await browser.close();
  server.close();
}
JS
node test-styleguide.mjs

Now prove it fails for the right reason. Keep a copy of tokens.css, write a version without --colour-on-accent (which the buttons, the selected slot and a contrast pair all use), run the test, then put the original back:

Bash
cp tokens.css tokens.css.bak
grep -v -- '--colour-on-accent:' tokens.css.bak > tokens.css
node test-styleguide.mjs
mv tokens.css.bak tokens.css

Check it worked

Each run first prints the server's line, Style guide at http://127.0.0.1:8124/. On the first run the next line is PASS: 47 tokens read. None missing. 13 semantic colours, all contrast pairs pass. The run with the token removed fails with an AssertionError whose message reads 46 tokens read. Missing: --colour-on-accent (components.css), and echo $? straight after it prints 1. After mv, run node test-styleguide.mjs once more and it passes again. In CI, run npx playwright install --with-deps chromium and then node test-styleguide.mjs as one job.

Step 8 · Clean up

Stop the server in its terminal with Ctrl+C. The files worth keeping are styleguide.html, styleguide.js, guide.css, serve.mjs and test-styleguide.mjs; copy them next to your own tokens.css if you want the guide in your project. Then remove the browser Playwright downloaded and the demo folder:

Bash
cd ~/styleguide-demo
npx playwright uninstall
cd ~
rm -rf ~/styleguide-demo

npx playwright uninstall removes the browsers this Playwright installation uses, unless another Playwright project on your machine still needs them. Skip it if you use Playwright elsewhere.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.