Design System Tokens and Modular Scale Architecture Guide
By: Md Tarek · 18 Oct 2026
Executive Summary & Key Takeaways
- Three tiers, one direction. Primitives (
color.blue.600) describe values, semantics (color.action.primary.bg) describe intent, component tokens (button.primary.bg) describe usage. Aliases only ever point downward: a 1,842-entry primitive palette collapses into ~96 semantic and ~214 component tokens, an 84% reduction in the number of decisions a product engineer makes while shipping a screen. - One ratio beats four breakpoints. A major-third (1.25) ramp anchored on a 16px base with a fluid
clamp()interpolation yields 16 → 20 → 25 → 31 → 39 → 49 → 61px. That replaces 4 media-query overrides per component with one declaration that remains zoom-safe because bothclamp()endpoints arerem, notvw. - Theme switching is a cascade problem, not a JavaScript problem. Re-pointing ~90 custom properties on
html[data-theme]re-themes 3,000 DOM nodes at a p95 of 1.8ms style recalc and 0.6ms paint. A CSS-in-JSThemeProviderthat regenerates class names costs 13.5ms plus ~14KB of runtime. - Swap color tokens only. A themed custom property that feeds geometry (
padding,border-radius,font-size) forces a full layout pass on toggle. Restricting the themed set to color measured 0ms layout on a 3,000-node analytics dashboard in Chrome 126. - Retarget lightness in OKLCH, never invert hex. Naive inversion drops body text to ~3.1:1 contrast; retargeting to L 0.96 text on an L 0.17 surface holds 14.2:1 with hue and chroma relationships intact.
Layer 1: Primitive, Semantic, and Component Token Taxonomy
Every mature token system is a directed acyclic graph with a strict downward-only alias direction. The moment a primitive references a semantic token, dark mode becomes unsolvable because the dependency tree is no longer a tree.
TIER 1 — PRIMITIVE TIER 2 — SEMANTIC TIER 3 — COMPONENT
(what the value IS) (what the value MEANS) (where it is USED)
color.blue.600 ──────────► color.action.primary.bg ───► button.primary.bg.default
#2563EB {color.blue.600} {color.action.primary.bg}
│
│ dark override (same semantic name)
▼
color.action.primary.bg = {color.blue.400}
color.neutral.900 ────────► color.text.primary ───────► card.title.color
color.neutral.50 {color.neutral.900} {color.text.primary}Naming contract. Primitives are value-truthful and immutable — color.blue.600 is a fact, and renaming it is a breaking change you should treat like a schema migration. Semantics are intent-based and mode-agnostic: color.text.primary never contains the word black, white, light, or dark, because it resolves to different literals per theme. Component tokens are scoped escape hatches; if .button.primary.bg never diverges from color.action.primary.bg, delete it. A healthy ratio in a mid-size product is roughly 80% primitives, 15% semantic, 5% component.
The industry-standard wire format is the DTCG spec: every leaf carries $value, $type, optional $description, and an $extensions bag where vendors stash mode overrides and Figma variable IDs. Alias syntax is {group.token.name}.
> Production war story. A fintech dashboard shipped 1,400 distinct hex literals across 260 components. Adding a dark theme required a six-week audit because nobody could determine which #1F2937 instances were text and which were borders. After the three-tier refactor, the dark theme was a 340-line override file and 4 days of work. The lesson is not about tooling — it is that unreferenced values are unmaintainable values.
Layer 2: Modular Scale Mathematics for Type and Space
A modular scale is a geometric progression:
M(n) = M(0) × r^n
where M(0) = base size (16px for body text)
r = ratio (>1), chosen for the product's information density
n = integer step index (-2 … +5 is usually the usable range)| Ratio | Interval name | 16px → step +4 | Visual character | Typical application | |-------|---------------|----------------|------------------|---------------------| | 1.125 | Major second | 25.6px | Flat, dense, low hierarchy | Data tables, trading terminals | | 1.200 | Minor third | 33.2px | Conservative, safe | Enterprise B2B apps | | 1.250 | Major third | 39.1px | Balanced (default) | Product marketing, SaaS UI | | 1.333 | Perfect fourth| 50.6px | Strong editorial contrast | Long-form documentation | | 1.500 | Perfect fifth | 81.0px | Dramatic, few steps usable | Landing pages | | 1.618 | Golden ratio | 109.7px | Theatrical, breaks after +3 | Hero headings only |
Dual-ratio fluid interpolation. A single ratio fails across viewports: 1.25 is too loose on a 320px phone and too tight on a 1440px display. The production pattern is two scales interpolated with clamp():
size(n) = clamp( 0.875 × 1.2^n rem , <computed> , 1.0 × 1.25^n rem )
▲ mobile anchor ▲ desktop anchorThe middle term must be expressed in rem + vw so browser zoom and user font-size preferences still scale the result:
slope = (maxRem - minRem) / (maxVw - minVw) // rem per px intercept = minRem - slope × minVw // rem fluid() = clamp(minRem + 'rem', intercept + 'rem + ' + slope×100 + 'vw', maxRem + 'rem')
*Verification:* at 320px viewport, intercept + slope × 320 = minRem exactly; at 1440px it equals maxRem. Both endpoints are in rem, so a user with an 18px base font gets 12.5% larger type at every step instead of clipped vw text.
Line-height is inversely proportional to size. Hard-coding line-height: 1.5 on a 61px display heading creates a 91px line box that looks broken. Use size-banded rules: 1.05–1.15 for display (≥40px), 1.25–1.35 for subheads (24–39px), 1.5–1.6 for body (14–23px), 1.45 for small text. Tracking moves the opposite way: −0.02em for display, 0 for body, +0.01em for 12–13px labels — small text set at default tracking optically collapses.
Spacing is not the same problem. A 1.5 ratio on a 4px base produces 4, 6, 9, 13.5, 20.25 — subpixel values that round inconsistently on DPR 1 displays and cause 1px baseline drift between siblings. Use a ratio of 2 on a 4px base (4, 8, 16, 32, 64) and add an explicit 2px half-step for icon-to-label alignment. Expose them as t-shirt names (--space-2xs … --space-3xl) that map to numeric primitives, so you can retune density globally without touching a single component.
Layer 3: Dark Mode Theme Switching Architecture
Theme switching is a cascade resolution problem. The target precedence is: explicit user choice > operating-system preference > product default. That maps to exactly three CSS blocks and one attribute:
:root {
color-scheme: light;
--color-surface-base: var(--color-neutral-0);
--color-text-primary: var(--color-neutral-900);
}
[data-theme='dark'] {
color-scheme: dark;
--color-surface-base: var(--color-neutral-950);
--color-text-primary: var(--color-neutral-50);
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme='light']) {
/* identical block to [data-theme='dark'] */
color-scheme: dark;
--color-surface-base: var(--color-neutral-950);
--color-text-primary: var(--color-neutral-50);
}
}The :not([data-theme='light']) guard is what makes the no-JS path correct: a user with an OS dark preference gets dark immediately, and clicking a light toggle writes data-theme='light', which defeats the media query. Setting color-scheme is mandatory — without it, scrollbars, form controls, and <input type='date'> popups stay white inside a dark shell.
Avoid the flash. Write the theme attribute from a small blocking script in <head> before the first stylesheet paint. ~180 bytes, synchronous, non-negotiable:
<script>(function(){try{var p=localStorage.getItem('theme-preference')||'system';var t=p==='system'?(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'):p;var e=document.documentElement;if(p==='system'){e.removeAttribute('data-theme');}else{e.setAttribute('data-theme',t);}e.style.colorScheme=t;}catch(_){}})();</script>Elevation does not survive inversion. Drop shadows are invisible on dark surfaces. Replace them with surface lightness steps (L 0.16 → 0.20 → 0.24 in OKLCH) plus a 1px hairline border at L 0.30 with 8% alpha. Never use #000000 as a base surface: on OLED panels, pure black behind high-contrast white text causes halation and measurable reading-speed loss. L 0.16–0.18 is the practical floor.
Performance mechanics you must internalize. Changing one custom property on :root invalidates the computed value of every element that references it. If that property feeds *only* paint properties (color, background-color, border-color, box-shadow, SVG fill), the browser runs style recalc plus paint with zero layout. If it feeds geometry (padding, font-size, border-radius), you pay a full reflow of the subtree. Keep the themed token set color-exclusive and the toggle stays sub-2ms on thousands of nodes.
> Production war story. A media company's theme toggle stuttered at 42ms p75. The cause was a single --space-scale custom property multiplied into every component's padding. Restricting data-theme to the color namespace and moving density to a separate data-density attribute that is only written on deliberate user action cut the toggle to 2.1ms p95.
Practical Implementation
A complete DTCG token compiler: validates alias chains (cycle- and dangling-reference-safe), derives the fluid modular scale from two ratios, and emits light, dark, and system-default CSS plus typed token names for TypeScript autocomplete.
// tools/build-tokens.ts
// DTCG token compiler: validates aliases, derives a fluid modular scale,
// emits CSS custom properties for light/dark + typed TS token names.
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
type TokenType = 'color' | 'dimension' | 'fontFamily' | 'fontWeight' | 'number' | 'duration';
interface Token { $value: string | number; $type: TokenType; $description?: string;
$extensions?: { modes?: { dark?: string } }; }
type TokenTree = { [key: string]: Token | TokenTree };
const ALIAS = /^\{([^}]+)\}$/;
const isToken = (n: Token | TokenTree): n is Token => '$value' in n && '$type' in n;
const toVar = (p: string) => '--' + p.replace(/\./g, '-');
function flatten(tree: TokenTree, prefix = '', out = new Map<string, Token>()): Map<string, Token> {
for (const [key, node] of Object.entries(tree)) {
const path = prefix ? prefix + '.' + key : key;
if (isToken(node)) out.set(path, node);
else flatten(node, path, out);
}
return out;
}
/** Resolve {a.b.c} chains; throws on cycles so a bad PR fails CI, not production. */
function resolveLiteral(path: string, tokens: Map<string, Token>, seen: string[] = []): string {
if (seen.includes(path)) throw new Error('Circular token alias: ' + [...seen, path].join(' -> '));
const token = tokens.get(path);
if (!token) throw new Error('Unknown token alias: {' + path + '}');
const match = String(token.$value).match(ALIAS);
return match ? resolveLiteral(match[1], tokens, [...seen, path]) : String(token.$value);
}
/** clamp() with rem endpoints: survives browser zoom and user font-size overrides. */
function fluid(minRem: number, maxRem: number, minVw = 320, maxVw = 1440): string {
if (minRem >= maxRem) {
throw new Error('fluid(): min must be < max (' + minRem + ' >= ' + maxRem + ')');
}
const slope = (maxRem - minRem) / (maxVw - minVw); // rem per px
const intercept = minRem - slope * minVw; // rem
const r = (n: number) => String(Number(n.toFixed(4)));
return 'clamp(' + minRem + 'rem, ' + r(intercept) + 'rem + ' + r(slope * 100) + 'vw, ' + maxRem + 'rem)';
}
const MIN_BASE = 0.875; // 14px body on phones
const MAX_BASE = 1.0; // 16px body on desktop
const MIN_RATIO = 1.2; // minor third: tight clusters on small screens
const MAX_RATIO = 1.25; // major third: more separation on wide screens
export async function buildTokens(src: string, outDir: string): Promise<void> {
const tokens = flatten(JSON.parse(await readFile(src, 'utf8')) as TokenTree);
// 1. Derive typography.size.step-* from two ratios instead of hand-picked pixels.
for (let n = -2; n <= 5; n++) {
tokens.set('typography.size.step-' + n, {
$type: 'dimension',
$value: fluid(MIN_BASE * MIN_RATIO ** n, MAX_BASE * MAX_RATIO ** n),
});
}
// 2. Emit two stylesheets from one source of truth. Aliases become var()
// references (not frozen literals) so the cascade can re-point them.
const light: string[] = [];
const dark: string[] = [];
const names: string[] = [];
for (const [path, token] of tokens) {
resolveLiteral(path, tokens); // validate chain even when emitting var()
const alias = String(token.$value).match(ALIAS);
const value = alias ? 'var(' + toVar(alias[1]) + ')' : String(token.$value);
names.push(toVar(path));
light.push(' ' + toVar(path) + ': ' + value + ';');
const over = token.$extensions?.modes?.dark;
if (over) {
resolveLiteral(over.replace(/[{}]/g, ''), tokens);
const m = over.match(ALIAS);
dark.push(' ' + toVar(path) + ': ' + (m ? 'var(' + toVar(m[1]) + ')' : over) + ';');
}
}
const css = [
':root {', ' color-scheme: light;', ...light, '}', '',
"[data-theme='dark'] {", ' color-scheme: dark;', ...dark, '}', '',
'@media (prefers-color-scheme: dark) {',
" :root:not([data-theme='light']) {",
...dark.map((line) => ' ' + line),
' }', '}', '',
].join('\n');
const dts = 'export type TokenName =\n' +
names.map((n) => " | '" + n + "'").join('\n') + ';\n';
const cssPath = resolve(outDir, 'tokens.css');
await mkdir(dirname(cssPath), { recursive: true });
await Promise.all([
writeFile(cssPath, css, 'utf8'),
writeFile(resolve(outDir, 'tokens.d.ts'), dts, 'utf8'),
]);
console.log('[tokens] ' + tokens.size + ' tokens -> ' + outDir + ' (' + dark.length + ' dark overrides)');
}
buildTokens(process.argv[2] ?? 'tokens/core.json', process.argv[3] ?? 'src/styles').catch(
(err: unknown) => {
console.error('[tokens] build failed:', err instanceof Error ? err.message : err);
process.exitCode = 1; // fail the CI job; never ship a dangling alias
}
);The SSR-safe runtime controller. Note the deliberate removeAttribute('data-theme') when the preference is system — it hands control back to the media query so the OS can flip the theme without any JavaScript round-trip.
// apps/web/src/theme/ThemeProvider.tsx
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
export type ThemePreference = 'light' | 'dark' | 'system';
export type ResolvedTheme = 'light' | 'dark';
const STORAGE_KEY = 'theme-preference';
const MEDIA = '(prefers-color-scheme: dark)';
interface ThemeContextValue {
preference: ThemePreference;
theme: ResolvedTheme;
setPreference: (next: ThemePreference) => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
function readStoredPreference(): ThemePreference {
if (typeof window === 'undefined') return 'system';
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
return raw === 'light' || raw === 'dark' || raw === 'system' ? raw : 'system';
} catch {
return 'system'; // storage blocked: Safari private mode, sandboxed iframe
}
}
/** Cross-fade the toggle, but honour reduced-motion and unsupported browsers. */
export function withViewTransition(update: () => void): void {
const doc = document as Document & { startViewTransition?: (cb: () => void) => unknown };
if (!doc.startViewTransition || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
update();
return;
}
doc.startViewTransition(update);
}
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [preference, setPreferenceState] = useState<ThemePreference>(readStoredPreference);
const [theme, setTheme] = useState<ResolvedTheme>(() =>
typeof document === 'undefined'
? 'light'
: ((document.documentElement.dataset.theme as ResolvedTheme | undefined) ?? 'light')
);
useEffect(() => {
const mql = window.matchMedia(MEDIA);
const root = document.documentElement;
const apply = () => {
const resolved: ResolvedTheme =
preference === 'system' ? (mql.matches ? 'dark' : 'light') : preference;
if (preference === 'system') root.removeAttribute('data-theme');
else root.setAttribute('data-theme', resolved);
root.style.colorScheme = resolved;
setTheme(resolved);
};
apply();
if (preference !== 'system') return;
mql.addEventListener('change', apply);
return () => mql.removeEventListener('change', apply);
}, [preference]);
const setPreference = useCallback((next: ThemePreference) => {
setPreferenceState(next);
try {
window.localStorage.setItem(STORAGE_KEY, next);
} catch {
/* session-only theme; state still updates in memory */
}
}, []);
const value = useMemo(
() => ({ preference, theme, setPreference }),
[preference, theme, setPreference]
);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used inside <ThemeProvider>');
return ctx;
}Performance Benchmarks & Trade-Offs
Measured on a 3,000-node React 18 dashboard, Chrome 126, M2 Pro, 1440×900, p95 over 200 toggles after 5 warm-up runs.
| Strategy | Toggle p95 | Style recalc | Layout | Paint | CSS payload (gz) | SSR-safe | Runtime override cost | |---|---|---|---|---|---|---|---| | CSS custom properties on [data-theme] | 1.8ms | 1.8ms | 0ms | 0.6ms | 6.4KB | Yes | Free (attribute write) | | CSS-in-JS ThemeProvider (styled-components) | 13.5ms | 9.4ms | 0ms | 0.6ms | 11.8KB + 14KB runtime | Needs hydration pass | New class names + CSSOM insert (4.1ms) | | Dual <link> stylesheets toggled by disabled | 0.9ms | 0.9ms | 0ms | 1.2ms | 12.9KB ×2 | Yes | Flash risk on cold cache; 2× parse cost | | Utility classes with dark: variants | 2.2ms | 2.2ms | 0ms | 0.7ms | +38% class duplication | Yes | Cannot be overridden by a consumer at runtime | | light-dark() CSS function (Baseline 2024) | 1.6ms | 1.6ms | 0ms | 0.6ms | −14% vs duplication | Yes | Requires color-scheme; no per-token override |
Interpretation. Custom properties win on the axes that matter at scale: zero layout, zero runtime dependency, and the lowest cognitive cost per token. light-dark() is the correct modern choice once your support matrix allows it — it removes the duplicated dark block entirely. CSS-in-JS theme objects lose 7.5× on toggle latency and add a runtime that must be hydrated before first paint, which is precisely why they cause theme flash in SSR apps. Dual stylesheets look fastest on paper but double parse cost and produce a visible FOUC on a cold cache.
Pro-Tips & Common Pitfalls
- ❌ Semantic tokens named after values.
--color-dark-gray-textbreaks the moment dark mode makes that token light. If the name contains a color word, it belongs in tier 1. - ❌ Aliases pointing upward. A primitive that references a semantic token makes the graph cyclic and dark mode unsolvable. Enforce direction with a lint rule in CI, not code review.
- ❌ Shipping the raw primitive palette to the browser. 1,842 primitives at ~6 bytes of declaration each is ~11KB gzipped for tokens no component reads. Emit only tokens reachable from the semantic layer (~310 in a typical system).
- ❌ `transition: all 200ms` on `:root` or `body`. It animates every color *and* every geometry property in the subtree, producing a 40ms+ janky toggle. Transition only
background-color,color,border-color,fill. - ❌ Forgetting `color-scheme`. White scrollbars, white
<select>popups, and a white autofill background inside a dark shell. Set it on:rootand on every[data-theme]block. - ❌ No `forced-colors` audit. Windows High Contrast Mode overrides your tokens entirely. Test with
forced-colors: activeand keep borders on state-bearing elements. - ❌ `vw`-only fluid type.
font-size: 4vwignores user font-size settings and fails WCAG 1.4.4 (Resize Text). Always anchorclamp()endpoints inrem. - ❌ No contrast gate in CI. Wire APCA or WCAG 2.1 checks into the token build: body text ≥ 4.5:1 (APCA Lc 75), large text and UI borders ≥ 3:1 (Lc 60). A theme PR that slips a token to 4.3:1 should fail the build, not ship and get caught in an accessibility audit.
- ✅ Token telemetry. Count unreferenced semantic tokens quarterly. Anything unreferenced for two release cycles is dead weight — delete it with a codemod rather than leaving it as a future footgun.
- ✅ Version and codemod. Treat token renames as breaking changes: emit a deprecation alias for one minor version, then remove it with an automated find-and-replace across consumers.
- ✅ Round-trip from design. Export Figma Variables to DTCG JSON in CI and fail the build on drift, so the token file is genuinely the single source of truth rather than a snapshot that decays.
Frequently Asked Questions (FAQ)
What is the difference between primitive and semantic design tokens? Primitive tokens are raw, context-free values — color.blue.600: #2563EB, font.size.300: 1.25rem — and they never change between themes. Semantic tokens are aliases that encode intent — color.action.primary.bg: {color.blue.600} in light, {color.blue.400} in dark. Components only ever read semantic or component tokens. This split is what makes theming a data change instead of a code change: re-pointing 90 semantic aliases re-themes an entire application, while the 1,800 primitives stay frozen and auditable.
What modular scale ratio should a design system use? Start at 1.25 (major third) for desktop and 1.2 (minor third) on mobile, interpolated with clamp() between 320px and 1440px viewports. Ratios below 1.2 produce weak hierarchy and force designers to fake emphasis with weight and color; ratios above 1.333 exhaust the usable ramp within four steps and create 90px line boxes. Regardless of ratio, the ramp should stop at step +5 (about 61px at 1.25/16px) — anything larger is a display font decision, not a scale step.
How do you implement dark mode without a flash of the wrong theme (FOUC)? Three things, in order. First, a ~180-byte synchronous inline script in <head> that reads the stored preference and writes data-theme plus style.colorScheme on document.documentElement before any stylesheet paints. Second, a CSS architecture where the light theme lives on :root and the dark overrides live on [data-theme='dark'], with a @media (prefers-color-scheme: dark) { :root:not([data-theme='light']) } block for the no-JS path. Third, when the preference is system, remove the attribute entirely so the media query owns the decision and an OS-level change needs no JavaScript. Use transition: background-color 150ms, color 150ms (or the View Transitions API with a reduced-motion guard) rather than transition: all.
