Frontend development · Beginner · 16 min
Turn design tokens into CSS custom properties
By Padding · Updated 18 Nov 2026
Modern browsers · CSS Custom Properties Level 1 · checked in Chromium 159 · Node.js 26
You will have a two-layer tokens.css file of primitive and semantic custom properties, component styles that use only the semantic layer, a Node script that enforces that rule, and a demo page that proves one primitive change reaches every component.
On this page
Larkfield Clinic's design team has split its colours, spacing and corner radius into two layers of tokens. Primitives such as teal/700 hold raw values. Semantic tokens such as colour/accent are named for a job and point at a primitive. The team wants the booking app's stylesheet to work the same way, so that a rebrand changes one line and a design decision changes one other line, and neither means a search-and-replace across the components.
CSS custom properties (often called CSS variables) are the browser's own way to do this. A custom property is any property whose name starts with two hyphens. You set it once, read it anywhere with var(), and one custom property can point at another. That last part is what makes two layers possible without any build tool.
In this tutorial you write the Larkfield tokens as custom properties in a single tokens.css, style a sample of booking app components using only the semantic layer, add a small Node script that fails if a component reaches past that layer, and check in the browser that changing one primitive moves every component that should move and nothing else. If you have not met the two layers before, Name design tokens from primitives to roles explains why they exist and how the names were chosen. You do not need Figma for this one.
Step 1 · Create the demo page
Make a folder and an HTML page holding a few pieces of the Larkfield booking app: the Pick a time heading, a row of morning time slots with 10:30 selected, a link, the two button styles, the banner from the Booked screen and an error message from Your details. Real screens come later; this page exists to show every token in use.
mkdir -p ~/tokens-demo
cd ~/tokens-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Larkfield tokens demo</title>
<link rel="stylesheet" href="tokens.css">
<link rel="stylesheet" href="components.css">
<script src="check-styles.js" defer></script>
</head>
<body>
<main class="screen">
<header>
<h1>Pick a time</h1>
<p class="muted">Nurse appointment, 15 min</p>
</header>
<section class="group" aria-labelledby="morning">
<h2 id="morning">Tue 9 Dec, morning</h2>
<ul class="slots">
<li><button class="slot" type="button" aria-pressed="false">09:00</button></li>
<li><button class="slot" type="button" aria-pressed="false">09:30</button></li>
<li><button class="slot" type="button" aria-pressed="false">10:00</button></li>
<li><button class="slot" type="button" aria-pressed="true">10:30</button></li>
<li><button class="slot" type="button" aria-pressed="false">11:00</button></li>
</ul>
<p class="muted">No time that suits you? <a href="#call">Call the clinic</a></p>
</section>
<div class="actions">
<button class="button-primary" type="button">Continue</button>
<button class="button-secondary" type="button">Back</button>
</div>
<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>
<p id="token-report" class="muted" role="status">Token check has not run</p>
</main>
</body>
</html>
HTMLThe page loads two stylesheets in a fixed order: tokens.css defines the values, components.css uses them. The script at the end is a check you write in a later step. The defer attribute runs it after the page is parsed and the stylesheets have loaded.
Check it worked
Run ls ~/tokens-demo. You see one file, index.html. Open it in a browser (drag the file into a window, or run open index.html on macOS or xdg-open index.html on Linux). It shows unstyled black text and default grey buttons, and the last line reads "Token check has not run". Both stylesheets are missing, so nothing is styled yet.
Step 2 · Write the primitive layer
Primitives are the raw values. Their names follow the Larkfield rule from the naming tutorial: a family (a hue, or a measure such as space) followed by a step number. In CSS the slash in teal/700 becomes a hyphen, because a custom property name cannot contain a slash without escaping, so teal/700 is written --teal-700.
Create tokens.css with the primitives inside a :root rule. :root matches the <html> element, the top of the page, so every element below it inherits the values:
cd ~/tokens-demo
cat > tokens.css <<'CSS'
/* Layer 1: primitives. Raw values, named family-step.
Components never use these directly. */
: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;
}
CSSThe spacing names keep the pixel value from the design file, but the values are in rem. At the default browser text size of 16 pixels, 1rem is 16 pixels, so --space-16 matches the design. When a reader raises their browser's text size, the spacing grows with the text instead of crowding it. Hex codes are written in lower case here; CSS treats #0F5E5A and #0f5e5a as the same colour.
Custom property names are case-sensitive, unlike most of CSS. --teal-700 and --Teal-700 are two different properties, which is one more reason to keep a single naming rule and write every name in lower case.
Check it worked
Run grep -c -- '^ --' tokens.css. It prints 19: twelve colours, six spacing values and one radius. Reload the page. It looks exactly the same as before, because nothing uses a primitive yet. That is correct: defining a custom property on its own changes nothing on screen.
Step 3 · Add the semantic layer
Semantic tokens are named for a job and hold no raw values. Each one points at a primitive with var(). Append them to the same file, in a second :root rule so the two layers are easy to tell apart:
cd ~/tokens-demo
cat >> tokens.css <<'CSS'
/* Layer 2: semantic tokens. Named for a job, and every value
is a primitive. 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);
}
CSSTwo things to notice. First, --colour-surface and --colour-on-accent both point at --grey-0. They are white today, but they are different jobs, and a later change (an off-white surface, say) moves one without the other.
Second, --space-inset-control is new. The Larkfield token table has no job for "padding inside a button or slot", and the components need one. The wrong fix is to write var(--space-12) straight into a component. The right fix is to add a role under the naming rule, point it at a primitive and record it in the token table. This also gives --space-12 its first job.
The naming rule pays off here: a primitive name always ends in a number and a semantic name never does. You can tell which layer a property belongs to from its name alone, and the script in a later step relies on exactly that.
Check it worked
These instructions are for Chrome or Edge DevTools. Open developer tools (F12, or Cmd+Option+I on macOS), choose the Elements panel and select the <html> element. In the Styles pane you see both :root rules, and --colour-accent reads var(--teal-700). Every semantic value in the file is a var() with no hex code or plain length. Firefox shows the same rules in its Inspector panel; in Safari, turn on the Develop menu in Safari's settings first, then use its Elements tab.
Step 4 · Style the components with semantic tokens only
Now write components.css. Every colour, gap, padding and corner radius comes from a semantic token. Font sizes stay as plain values here; type tokens get their own treatment in Build fluid type with CSS clamp().
cd ~/tokens-demo
cat > components.css <<'CSS'
* { box-sizing: border-box; }
body {
margin: 0;
font-family: Inter, system-ui, sans-serif;
line-height: 1.5;
background: var(--colour-canvas);
color: var(--colour-text);
}
.screen {
max-width: 24rem;
margin: 0 auto;
padding: var(--space-inset-screen);
display: flex;
flex-direction: column;
gap: var(--space-stack-l);
}
h1, h2, p { margin: 0; }
h1 { font-size: 1.75rem; line-height: 1.2; }
h2 { font-size: 1.25rem; line-height: 1.3; }
.muted { color: var(--colour-text-muted); font-size: 0.875rem; }
a { color: var(--colour-accent); }
.group {
display: flex;
flex-direction: column;
gap: var(--space-stack-m);
padding-bottom: var(--space-stack-m);
border-bottom: 1px solid var(--colour-line);
}
.slots {
display: flex;
flex-wrap: wrap;
gap: var(--space-stack-s);
margin: 0;
padding: 0;
list-style: none;
}
.slot {
min-height: 48px;
padding: 0 var(--space-inset-control);
font: inherit;
background: var(--colour-surface);
color: var(--colour-text);
border: 1px solid var(--colour-border);
border-radius: var(--radius-control);
}
.slot[aria-pressed="true"] {
background: var(--colour-accent);
color: var(--colour-on-accent);
border-color: var(--colour-accent);
}
.actions {
display: flex;
flex-direction: column;
gap: var(--space-stack-s);
margin-top: var(--space-stack-xl);
}
.button-primary,
.button-secondary {
min-height: 48px;
padding: 0 var(--space-inset-control);
font: inherit;
font-weight: 600;
border-radius: var(--radius-control);
}
.button-primary {
background: var(--colour-accent);
color: var(--colour-on-accent);
border: 1px solid var(--colour-accent);
}
.button-secondary {
background: var(--colour-surface);
color: var(--colour-accent);
border: 1px solid var(--colour-border);
}
.banner {
padding: var(--space-inset-control);
background: var(--colour-accent-tint);
color: var(--colour-text);
border-radius: var(--radius-control);
}
.error {
padding: var(--space-inset-control);
background: var(--colour-danger-tint);
color: var(--colour-danger);
border: 1px solid var(--colour-danger);
border-radius: var(--radius-control);
}
CSSRead any rule and you can say what each value is for: the selected slot uses the accent, its text sits on the accent, its corners are a control's corners. Nothing in this file says teal or 12 pixels. That knowledge lives in one place, tokens.css.
A typo in a token name fails quietly. If you write var(--colour-acent), the browser cannot find the property, the declaration becomes invalid when the page is styled, and the element falls back to an inherited or default value: a transparent button, black text. There is no error in the console. You can give var() a fallback as a second argument, as in var(--colour-accent, #0f5e5a), but in a token system that hides the typo instead of fixing it. The script in the next step catches it instead.
Check it worked
Reload the page. The background is a very light grey, the 10:30 slot is dark teal with white text, the other slots are white with a grey border, Continue is a full-width teal button, Back is white with teal text, the Booked banner is pale teal, and the error message is dark red on pale red. Every slot, button and box has the same rounded corners.
Step 5 · Check that components use only semantic tokens
Rules that live only in people's heads get broken under deadline. Write a short Node script that reads both files and reports three kinds of problem: a component using a token that does not exist, a component using a primitive, and a semantic token holding a raw value instead of pointing at a primitive. It also flags hex and rgb() colours typed straight into components.
cd ~/tokens-demo
cat > check-tokens.mjs <<'JS'
import { readFileSync } from 'node:fs';
const [tokensFile = 'tokens.css', componentsFile = 'components.css'] = process.argv.slice(2);
const tokens = readFileSync(tokensFile, 'utf8');
const components = readFileSync(componentsFile, 'utf8');
const isPrimitive = (name) => /-\d+$/.test(name);
const problems = [];
const defined = new Map();
for (const [, name, value] of tokens.matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/g)) {
defined.set(name, value.trim());
}
for (const [name, value] of defined) {
if (!isPrimitive(name) && !/^var\(--[a-z]+-\d+\)$/.test(value)) {
problems.push(`${tokensFile}: ${name} should point at a primitive, not hold ${value}`);
}
}
const used = new Set([...components.matchAll(/var\(\s*(--[a-z0-9-]+)/g)].map((m) => m[1]));
for (const name of used) {
if (!defined.has(name)) problems.push(`${componentsFile}: ${name} is not defined in ${tokensFile}`);
else if (isPrimitive(name)) problems.push(`${componentsFile}: ${name} is a primitive; use a semantic token`);
}
for (const raw of components.match(/#[0-9a-fA-F]{3,8}\b|rgba?\(/g) ?? []) {
problems.push(`${componentsFile}: raw colour ${raw} instead of a token`);
}
if (problems.length) {
console.log(problems.join('\n'));
process.exitCode = 1;
} else {
const semantic = [...defined.keys()].filter((n) => !isPrimitive(n)).length;
console.log(`OK: ${defined.size - semantic} primitives, ${semantic} semantic tokens, ${used.size} used by components`);
}
JS
node check-tokens.mjsThe script leans on the naming rule: "ends in a number" means primitive. That is why the rule was written before the tokens were named. It is a deliberately small check, built from regular expressions rather than a CSS parser, which is enough for one tokens file and one components file written in this style.
Now see it catch a mistake. Make a scratch stylesheet that breaks all three rules, run the check against it, then delete it:
cat > bad.css <<'CSS'
.promo { color: var(--teal-700); background: #fafafa; border-color: var(--colour-acent); }
CSS
node check-tokens.mjs tokens.css bad.cssrm bad.cssCheck it worked
The first run prints OK: 19 primitives, 20 semantic tokens, 18 used by components. The run against bad.css prints three lines, one for --teal-700 being a primitive, one for --colour-acent not being defined, and one for the raw colour #fafafa, and it exits with a non-zero status (echo $? straight after it prints 1). Two semantic tokens, --colour-notice and --colour-notice-tint, are defined but not used on this page. The script does not complain about that, because a token system usually defines more than one page needs.
Run node check-tokens.mjs before every commit, or add it to your CI. It needs no packages and no network, so it runs the same on a laptop with no data left as it does on a build server.
Step 6 · Prove one primitive change reaches every component
The point of the two layers is that a rebrand changes one primitive and every job that uses it follows. Write a small browser script that reads computed styles, changes --teal-700 for a moment, and checks that the accent parts of the page all moved. The page already loads check-styles.js, so create it:
cd ~/tokens-demo
cat > check-styles.js <<'JS'
(() => {
const rgb = (hex) => {
const n = parseInt(hex.slice(1), 16);
return `rgb(${n >> 16}, ${(n >> 8) & 255}, ${n & 255})`;
};
const read = (selector, property) =>
getComputedStyle(document.querySelector(selector))[property];
const results = [];
const expect = (label, actual, wanted) =>
results.push({ label, ok: actual === wanted, actual, wanted });
const accentParts = [
['.button-primary', 'backgroundColor'],
['.slot[aria-pressed="true"]', 'backgroundColor'],
['.button-secondary', 'color'],
['a', 'color'],
];
for (const [sel, prop] of accentParts) expect(`${sel} ${prop} is the accent`, read(sel, prop), rgb('#0f5e5a'));
expect('banner uses accent-tint', read('.banner', 'backgroundColor'), rgb('#e3f0ee'));
expect('error text uses danger', read('.error', 'color'), rgb('#b42318'));
const root = document.documentElement;
root.style.setProperty('--teal-700', '#6b2fa0');
for (const [sel, prop] of accentParts) expect(`${sel} ${prop} follows --teal-700`, read(sel, prop), rgb('#6b2fa0'));
root.style.removeProperty('--teal-700');
expect('accent is back after the test', read('.button-primary', 'backgroundColor'), rgb('#0f5e5a'));
const passed = results.filter((r) => r.ok).length;
console.table(results);
const report = document.querySelector('#token-report');
report.textContent = `Token check: ${passed} of ${results.length} passed`;
report.dataset.ok = String(passed === results.length);
})();
JSgetComputedStyle returns the value the browser actually uses after every var() has been resolved, and it reports colours in rgb() form, so the script converts the expected hex codes before comparing. Setting --teal-700 with style.setProperty on the <html> element overrides the primitive at the top of the page, and removing it puts the original back before anyone sees the change.
The script changed one primitive and touched no component rule. If the Continue button, the selected slot, the Back label and the link all turned purple, they really do reach the colour through --colour-accent and nothing else.
Check it worked
Reload the page. The last line now reads "Token check: 11 of 11 passed". Open the Console in developer tools and you see the same eleven rows in a table, each with ok set to true. If a row fails, its actual and wanted columns show which colour came out wrong, and the cause is almost always a component using a raw value or the wrong token.
Try the change by hand too. In the Console, run:
document.documentElement.style.setProperty('--teal-700', '#6b2fa0')The selected slot, Continue, the Back label and the link turn purple at once. The pale banner, the borders and the error message do not change. Reload to put the teal back. Some browsers ask you to type a phrase such as "allow pasting" before they accept pasted code in the Console; typing the line avoids that.
Step 7 · Change a decision without touching a value
The second kind of change is a design decision: "the Booked banner should sit on the canvas grey, not the pale teal". That changes which primitive a semantic token points at. No raw value moves, and other jobs that share the primitive stay put. In the Console, run:
document.documentElement.style.setProperty('--colour-accent-tint', 'var(--grey-50)')In a real project you would make the same change in tokens.css by editing one line, --colour-accent-tint: var(--grey-50);, and commit it with a note of why.
Where you override a token matters
Now try the rebrand from the previous step on a part of the page instead of the whole page. In the Console, reload, then run:
document.querySelector('.slots').style.setProperty('--teal-700', '#6b2fa0')The selected 10:30 slot stays teal. This is how custom properties inherit: the browser resolves --colour-accent: var(--teal-700) on the <html> element, where the semantic token is declared, and passes the finished colour down. A child receives the colour, not the formula, so changing --teal-700 lower down has nothing left to change.
The rule that follows: override primitives where the semantic tokens are declared, on :root, and when one part of a page needs a different look, re-point the semantic token in that part instead. For example, .slots { --colour-accent: var(--amber-700); } does change the selected slot, because the semantic token itself is now declared on .slots. Theming works the same way: Add dark mode with CSS variables swaps colour values for a dark theme, and with two layers you would do it by re-pointing the semantic tokens on :root at darker primitives.
Check it worked
After the decision change, the Booked banner is light grey and the selected slot and Continue are still teal, even though the canvas and the banner now share --grey-50. After the scoped experiment, the selected slot stayed teal when you changed --teal-700 on .slots, and turns dark amber if you run document.querySelector('.slots').style.setProperty('--colour-accent', 'var(--amber-700)'). Reload to undo everything; the report line goes back to "Token check: 11 of 11 passed".
Step 8 · Clean up
The three files you keep are tokens.css, components.css and check-tokens.mjs. Copy them into your own project if you want them, then remove the demo folder:
cd ~
rm -rf ~/tokens-demoCustom properties work in every current browser, including Chrome for Android and Samsung Internet on budget phones, and need no build step. tokens.css is one small file that a phone downloads once and caches for every page that links it.
Next steps
- Generate CSS from a token file with Style Dictionary keeps the tokens in one JSON file and writes
tokens.cssfor you, along with a JavaScript module. - Add dark mode with CSS variables gives the page a second theme.
- Name design tokens from primitives to roles is the design side of this tutorial, where the token names come from.
Part of these paths
Related tutorials
- Name design tokens from primitives to rolesYou will have the Larkfield Clinic values split into a primitives collection and a semantic collection in Figma variables, every semantic token aliasing a primitive, and a one-paragraph naming rule your team can apply to any new token.
- Generate CSS from a token file with Style DictionaryYou will have the Larkfield Clinic design tokens in JSON files, a Style Dictionary build that turns them into CSS custom properties and a JavaScript module with one npm script, and a build that fails loudly when a token reference is broken, so it can run in CI.
- How to Add Dark Mode to a Website with CSS VariablesYou will define your colours once as CSS custom properties, switch them with light-dark() and the user's system setting, add a toggle button that remembers the choice without a flash on reload, and check the text contrast of both themes with a short script.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials