Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Design

Design System Tokens and Modular Scale Architecture Guide

By: Md Tarek · 21 Oct 2026

Design system tokens architecture: primitive and semantic token layers feeding a modular type scale and OKLCH dark mode theme switching
Design system tokens architecture: primitive and semantic token layers feeding a modular type scale and OKLCH dark mode theme switching

Executive Summary & Key Takeaways

  • A three-tier token graph (primitive to semantic to component) is the only structure that survives multi-brand theming. In our reference system, 412 primitive values and 214 semantic roles replaced 1,180 hard-coded literals; dark mode shipped as a 3.9 KB gzip override block instead of a duplicated stylesheet, cutting total design-system CSS from 41.2 KB to 11.8 KB gzip.
  • Alias resolution belongs at build time, not runtime. A DFS resolver with tri-state cycle detection adds 0.4 s to CI and permanently eliminates the bug class where an alias chain silently resolves to an empty declaration.
  • Modular typography at ratio 1.25 (major third), anchored at 16 px and fluidly interpolated between 360 px and 1440 px viewports, collapses 63 ad-hoc font sizes into 9 steps and holds cumulative layout shift at 0.000 across 40 audited templates.
  • Dark mode is a lightness-space operation, not an inversion. Deriving dark surfaces in OKLCH with hue held constant and chroma reduced to roughly 72% kept APCA Lc >= 75 on every body-text pairing; naive RGB inversion failed 34% of those same pairings at WCAG 2.2 AA (4.5:1).
  • Theme switching costs a full style recalculation, so budget it. 12,400 elements x 626 inherited custom properties measured 6.8 ms p50 / 14.2 ms p99 on a Pixel 4a; marking component-scoped tokens inherits: false via @property dropped p50 to 4.1 ms with zero payload change.

Architecture 1: The Three-Tier Token Graph

Most teams that say they 'have design tokens' actually have a color palette. A palette is a list; a token system is a directed acyclic graph with a strict layering contract. The contract is what makes rebrands cheap and what makes dark mode a 200-line diff instead of a fork.

Tier 1 - Primitives (raw, theme-agnostic, exhaustive)

Primitives are the full material library: complete color ramps, the dimension ramp, font stacks, weights, durations, easings, shadows. They are named by *value family*, never by *intent*: color.blue.500, color.neutral.950, dimension.space.4, duration.fast.100. Product code must never reference these.

Tier 2 - Semantics (role-based, theme-dependent, public API)

Semantics are the only tokens application code is allowed to consume: color.surface.base, color.text.muted, color.action.bg, color.border.subtle, space.stack.md, type.body.md. Each semantic is an alias to a primitive, and a theme is nothing more than a re-pointing of that alias table.

Tier 3 - Components (the escape hatch, scoped)

button.primary.bg, card.padding. Component tokens alias semantics only. They exist so a component can be re-skinned without inventing new semantics, and they should be emitted inside the component's CSS layer rather than on :root.

 primitives (412)                 semantic (214)                component (lazy)
+------------------------+      +-------------------------+    +---------------------+
| color.blue.500         |----->| color.action.bg         |--->| button.primary.bg   |
| color.blue.600         |--+   | color.action.bg.hover   |    | button.primary.fg   |
| color.neutral.0        |  +-->| color.text.onAction     |    +---------------------+
| color.neutral.950      |      | color.surface.base      |--->| card.bg             |
| dimension.space.4      |----->| space.stack.md          |    | card.padding        |
+------------------------+      +-------------------------+    +---------------------+
        ^                                  ^
        |                                  |
  themes/dark.json                 identical alias graph,
  re-points aliases                different resolved primitives

Why CSS custom properties and not precompiled values

Precompiled tokens (SCSS variables, compiled Tailwind theme values) are dead at runtime. Every theme change requires a re-render or a full stylesheet swap, which is exactly the 20-60 ms jank we measured later in this article. CSS custom properties live in the cascade: changing one attribute on <html> invalidates the whole tree at C++ speed, with no JavaScript reconciler in the loop.

Production war story. A fintech client asked for a 'simple' accent-color rebrand. Scope estimate: 2 days. Reality: 17 days, because 41% of component styles imported primitives directly (var(--blue-500)), and three teams had locally forked the button. We spent 14 of those days migrating call sites to semantics. The next rebrand took 1.5 days. The lesson is mechanical: enforce the tier contract with a build-time lint, because code review alone will not hold it.

Enforcing the contract

  • Primitives may not alias other primitives (except dimension ramps).
  • Semantics may alias a primitive or one other semantic, maximum two hops.
  • Components may alias semantics only.
  • No two token paths may collapse to the same CSS name. color.action.bg and color.action-bg both become --color-action-bg, so forbid dashes inside path segments.

Architecture 2: Mathematical Typography and Modular Spacing

A type scale is a geometric sequence: size(n) = base * r^n. The ratio r is a design decision with measurable consequences, and the naive single-ratio scale breaks at both ends of the viewport range.

Choosing the ratio

| Ratio | Name | Step +4 at 16 px base | Screen presence | Best fit | |---|---|---|---|---| | 1.125 | Major second | 25.6 px | Subtle | Dense dashboards, data tables | | 1.200 | Minor third | 33.2 px | Balanced | Product and app UI (default) | | 1.250 | Major third | 39.1 px | Confident | Hybrid marketing plus product | | 1.333 | Perfect fourth | 50.6 px | Editorial | Long-form content, blogs | | 1.414 | Augmented fourth | 64.0 px | Dramatic | Hero-led landing pages | | 1.500 | Perfect fifth | 81.0 px | Poster | Campaign microsites | | 1.618 | Golden ratio | 109.7 px | Theatrical | Display only, max 4 steps |

Anything above 1.333 is unusable as a *global* scale because step -1 through +2 grow too fast for UI chrome nested inside content. The pattern that actually ships: two ratios on one scale - a tight ratio at the small end and a looser one at the display end.

The nine-step ramp with fluid interpolation

Our shipped ramp uses r = 1.2 at 360 px and r = 1.25 at 1440 px, with the base itself interpolating from 16 px to 18 px. Interpolation is linear in viewport width, then clamped:

slope      = (maxPx - minPx) / (vwMax - vwMin) * 100   -> vw units
intercept  = minPx - (slope / 100) * vwMin             -> rem units
value      = clamp(minPx, intercept + slope * 1vw, maxPx)

Worked example for step +4: min = 16 x 1.2^4 = 33.1776 px, max = 16 x 1.25^4 = 39.0625 px over 1080 px of viewport travel. Slope = 5.8849 / 1080 = 0.005449 px/px = 0.5449vw. Intercept = 33.1776 - (0.5449 x 3.6) = 31.216 px = 1.951rem. Verification at 1440 px: 31.216 + (0.5449 x 14.4) = 39.0626 px. Exact.

:root {
  /* base: 16px at 360w -> 18px at 1440w */
  --step-0: clamp(1rem, 0.9583rem + 0.18519vw, 1.125rem);
  --step--1: clamp(0.8rem, 0.7813rem + 0.0833vw, 0.9rem);
  --step-1: clamp(1.2rem, 1.1354rem + 0.2870vw, 1.4063rem);
  --step-4: clamp(2.0736rem, 1.951rem + 0.5449vw, 2.4414rem);
  --step-7: clamp(4.2998rem, 3.8763rem + 1.8820vw, 5.625rem);

  --leading-display: 1.08;
  --leading-heading: 1.22;
  --leading-body: 1.55;
}

Line height should decrease as size increases (inverse relationship): display text at 1.05-1.15, headings at 1.2-1.3, body at 1.5-1.6. Setting 1.5 everywhere produces visibly gappy headlines; setting it per-step in the token layer is the only maintainable fix.

Modular spacing without magic numbers

Spacing needs two different behaviours at two different magnitudes. Small gaps must sit on a hard 4 px grid so they align to icon baselines and border radii; large gaps must grow geometrically so section rhythm scales with viewport. A single ramp doing both produces either absurd 4 px-step noise at the top or cramped 1 px gaps at the bottom.

--space-1 .. --space-6   linear, 4px grid:  4, 8, 12, 16, 20, 24
--layout-1 .. --layout-8 modular r=1.5, rounded to nearest 4px:
                            48, 72, 108, 160, 240, 360, 540, 810

Use rem for spacing, not px. At 200% browser zoom a px-based layout keeps the same physical gaps while text doubles, and the composition collapses. rem scales both together, which is what accessibility audits expect.

Architecture 3: Dark Mode as a Lightness-Space Operation

Dark mode is not filter: invert(1), and it is not an HSL hue rotation. Both operations destroy hue fidelity and contrast. The correct model is per-role remapping in a perceptually uniform color space.

Why OKLCH

OKLCH encodes lightness (l, 0-1), chroma (c, roughly 0-0.4) and hue (h, degrees) so that equal l deltas look like equal brightness deltas to the human visual system. This gives you two properties you cannot get from sRGB or HSL:

1. Hue stability under lightness change. Holding h fixed while moving l from 0.42 to 0.78 gives the same color, lighter. In HSL, hsl(220 90% 30%) and hsl(220 90% 80%) are perceptually different hues. 2. Predictable contrast. An APCA Lc of 75 corresponds to a roughly consistent l delta, so you can validate an entire theme with arithmetic instead of 214 manual spot checks.

The remapping rules we ship

| Role family | Light l | Dark l | Chroma multiplier | Notes | |---|---|---|---|---| | Surface (elevation ladder) | 0.99 / 0.97 / 0.95 | 0.145 / 0.187 / 0.229 | 0.006 base | Never pure black; OLED halation | | Text primary | 0.21 | 0.96 | 0.20 | Never pure white | | Text muted | 0.45 | 0.72 | 0.30 | Watch Lc on raised surfaces | | Accent fill | 0.55 | 0.68 | 0.85 | Dark needs lighter, calmer accents | | Accent text on surface | 0.48 | 0.80 | 0.75 | Verify Lc >= 75 | | Borders | 0.90 | 0.28 | 0.50 | Elevation reads via border, not shadow |

Two rules earn their keep. Elevation in dark mode comes from lightness steps plus a 1 px border, not from drop shadows - shadows are invisible against dark surfaces. And never use `oklch(0% 0 0)` as a background: on OLED panels, pure black next to mid-tone content produces halation and visible subpixel smear during scroll on 120 Hz displays.

Gamut mapping

Wide-chroma accents routinely fall outside sRGB. Browsers will gamut-map for you, but they do it inconsistently across engines, which means your token color and the rendered color diverge per browser. Clamp at build time by bisecting on chroma:

OKLCH (l, c, h) -> linear sRGB via LMS cube
      |
      +-- all channels in [0-EPS, 1+EPS]? --yes--> emit oklch()
      |
      +-- no --> bisect c in [0, c] for 18 iterations
                 -> keep largest in-gamut chroma -> emit

This converges to within 4e-6 chroma, which is far below perceptual thresholds, and produces identical output in Chrome, Safari, and Firefox.

Practical Implementation

1. The token compiler (build time)

This compiles tokens/core.json into a single layered stylesheet, validating the schema, resolving the alias graph, and failing the build on cycles.

// tokens/build.ts - deterministic token compiler.
// Validates schema, resolves the alias DAG with cycle detection, emits layered CSS.
// Usage: tsx tokens/build.ts src/styles/tokens.css

import { z } from 'zod';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';

interface TokenLeaf {
  $value: string | number;
  $type: 'color' | 'dimension' | 'fontFamily' | 'fontWeight' | 'duration' | 'shadow' | 'easing';
  $description?: string;
}

type TokenGroup = { [key: string]: TokenLeaf | TokenGroup };

const LeafSchema = z.object({
  $value: z.union([z.string().min(1), z.number()]),
  $type: z.enum(['color', 'dimension', 'fontFamily', 'fontWeight', 'duration', 'shadow', 'easing']),
  $description: z.string().optional(),
});

const GroupSchema: z.ZodType<TokenGroup> = z.lazy(() =>
  z.record(z.union([LeafSchema, GroupSchema])),
) as z.ZodType<TokenGroup>;

const FileSchema = z.object({
  primitive: GroupSchema,
  semantic: GroupSchema,
  themes: z.record(z.string(), z.record(z.string(), z.string())),
});

class TokenError extends Error {
  constructor(message: string, readonly path: string) {
    super(message + ' at ' + path);
    this.name = 'TokenError';
  }
}

function isLeaf(node: TokenLeaf | TokenGroup): node is TokenLeaf {
  return typeof (node as TokenLeaf).$value !== 'undefined';
}

function flatten(
  group: TokenGroup,
  prefix = '',
  into = new Map<string, TokenLeaf>(),
): Map<string, TokenLeaf> {
  for (const [key, node] of Object.entries(group)) {
    if (key.startsWith('$')) continue;
    const path = prefix ? prefix + '.' + key : key;
    if (isLeaf(node)) into.set(path, node);
    else flatten(node, path, into);
  }
  return into;
}

function parseAlias(raw: string): string | null {
  return raw.length > 2 && raw[0] === '{' && raw.endsWith('}') ? raw.slice(1, -1) : null;
}

interface Resolved {
  path: string;
  value: string;
  type: TokenLeaf['$type'];
}

function resolveTheme(
  primitives: Map<string, TokenLeaf>,
  semantics: Map<string, TokenLeaf>,
  overrides: Record<string, string>,
): Map<string, Resolved> {
  const roots = new Map(semantics);
  for (const [path, alias] of Object.entries(overrides)) {
    const base = semantics.get(path);
    if (!base) throw new TokenError('Theme override targets an unknown semantic token', path);
    roots.set(path, { ...base, $value: alias });
  }

  const state = new Map<string, 'visiting' | 'done'>();
  const out = new Map<string, Resolved>();

  const visit = (path: string, stack: string[]): string => {
    const cached = out.get(path);
    if (cached) return cached.value;
    if (state.get(path) === 'visiting') {
      throw new TokenError('Cyclic alias chain: ' + stack.concat(path).join(' -> '), path);
    }
    const node = roots.get(path) ?? primitives.get(path);
    if (!node) throw new TokenError('Unresolved token reference', path);

    state.set(path, 'visiting');
    const raw = String(node.$value);
    const alias = parseAlias(raw);
    const value = alias ? visit(alias, stack.concat(path)) : raw;
    state.set(path, 'done');

    out.set(path, { path, value, type: node.$type });
    return value;
  };

  for (const path of roots.keys()) visit(path, []);
  return out;
}

const cssCustomProperty = (path: string): string => '--' + path.split('.').join('-');

function emitBlock(selector: string, tokens: Map<string, Resolved>): string {
  const body = Array.from(tokens.values())
    .sort((a, b) => a.path.localeCompare(b.path))
    .map((token) => '  ' + cssCustomProperty(token.path) + ': ' + token.value + ';')
    .join('\n');
  return selector + ' {\n' + body + '\n}';
}

async function main(): Promise<void> {
  const outPath = resolve(process.argv[2] ?? 'src/styles/tokens.css');
  try {
    const raw: unknown = JSON.parse(await readFile('tokens/core.json', 'utf8'));
    const parsed = FileSchema.parse(raw);

    const primitives = flatten(parsed.primitive);
    const semantics = flatten(parsed.semantic);

    const light = resolveTheme(primitives, semantics, parsed.themes.light ?? {});
    const dark = resolveTheme(primitives, semantics, parsed.themes.dark ?? {});

    const css = [
      '/* GENERATED FILE - do not edit. Source: tokens/core.json */',
      '@layer tokens {',
      emitBlock(':root', light),
      emitBlock(`:root[data-theme='dark']`, dark),
      '}',
      '',
    ].join('\n');

    await mkdir(dirname(outPath), { recursive: true });
    await writeFile(outPath, css, 'utf8');
    console.log('tokens: ' + light.size + ' roles x 2 themes -> ' + outPath);
  } catch (error) {
    if (error instanceof TokenError) {
      console.error('token graph error: ' + error.message);
    } else if (error instanceof z.ZodError) {
      console.error(
        'schema error: ' + error.issues.map((i) => i.path.join('.') + ': ' + i.message).join('; '),
      );
    } else {
      throw error;
    }
    process.exitCode = 1;
  }
}

void main();

A representative tokens/core.json for the dark override block stays tiny - 214 alias re-points, 3.9 KB gzip - because it contains no repeat values, only pointers:

{
  "themes": {
    "light": {},
    "dark": {
      "color.surface.base": "{color.neutral.950}",
      "color.surface.raised": "{color.neutral.900}",
      "color.text.primary": "{color.neutral.50}",
      "color.action.bg": "{color.blue.400}"
    }
  }
}

2. OKLCH math and the dark surface ladder

// tokens/color.ts - sRGB gamut clamping and the dark elevation ladder.
export interface Oklch {
  l: number;
  c: number;
  h: number;
}

const EPSILON = 0.0002;

function oklchToLinearRgb({ l, c, h }: Oklch): [number, number, number] {
  const hr = (h * Math.PI) / 180;
  const a = c * Math.cos(hr);
  const b = c * Math.sin(hr);

  const lp = l + 0.3963377774 * a + 0.2158037573 * b;
  const mp = l - 0.1055613458 * a - 0.0638541728 * b;
  const sp = l - 0.0894841775 * a - 1.291485548 * b;

  const l3 = lp ** 3;
  const m3 = mp ** 3;
  const s3 = sp ** 3;

  return [
    4.0767416621 * l3 - 3.3077115913 * m3 + 0.2309699292 * s3,
    -1.2684380046 * l3 + 2.6097574011 * m3 - 0.3413193965 * s3,
    -0.0041960863 * l3 - 0.7034186147 * m3 + 1.707614701 * s3,
  ];
}

const inGamut = (rgb: [number, number, number]): boolean =>
  rgb.every((channel) => channel >= -EPSILON && channel <= 1 + EPSILON);

export function clampToSrgb(color: Oklch): Oklch {
  if (inGamut(oklchToLinearRgb(color))) return color;

  let lo = 0;
  let hi = color.c;
  for (let i = 0; i < 18; i += 1) {
    const mid = (lo + hi) / 2;
    if (inGamut(oklchToLinearRgb({ ...color, c: mid }))) lo = mid;
    else hi = mid;
  }
  return { ...color, c: Number(lo.toFixed(4)) };
}

export const formatOklch = ({ l, c, h }: Oklch): string =>
  `oklch(${(l * 100).toFixed(2)}% ${c.toFixed(4)} ${h.toFixed(1)})`;

// Elevation ladder: 0 = page, 1 = card, 2 = popover, 3 = modal.
export function darkSurface(hue: number, elevation: number): string {
  const l = 0.145 + 0.042 * elevation;
  const c = 0.006 + 0.0035 * elevation;
  return formatOklch(clampToSrgb({ l, c, h: hue }));
}

3. Runtime theme controller with no flash and no jank

The blocking inline script below must be the first thing in <head>, before any stylesheet link. It costs about 0.3 ms of parse-blocking time and is the only reliable way to avoid a flash of the wrong theme.

<script>
  (function () {
    try {
      var stored = localStorage.getItem('theme-mode') || 'system';
      var prefersDark = matchMedia('(prefers-color-scheme: dark)').matches;
      var dark = stored === 'dark' || (stored === 'system' && prefersDark);
      var root = document.documentElement;
      root.dataset.theme = dark ? 'dark' : 'light';
      root.style.colorScheme = dark ? 'dark' : 'light';
    } catch (error) {
      document.documentElement.dataset.theme = 'light';
    }
  })();
</script>
// src/theme/controller.ts - mode resolution, persistence, OS sync, view transitions.
export type ThemeMode = 'light' | 'dark' | 'system';
type ResolvedTheme = 'light' | 'dark';

const STORAGE_KEY = 'theme-mode';
const media = window.matchMedia('(prefers-color-scheme: dark)');
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');

function readStoredMode(): ThemeMode {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw === 'light' || raw === 'dark' || raw === 'system') return raw;
  } catch {
    // Safari private mode and storage-denied iframes throw on access.
  }
  return 'system';
}

let currentMode: ThemeMode = readStoredMode();

export function resolveMode(mode: ThemeMode): ResolvedTheme {
  if (mode !== 'system') return mode;
  return media.matches ? 'dark' : 'light';
}

function applyTheme(theme: ResolvedTheme, animate: boolean): void {
  const root = document.documentElement;

  const commit = (): void => {
    root.dataset.theme = theme;
    root.style.colorScheme = theme;
    document
      .querySelector('meta[name=theme-color]')
      ?.setAttribute('content', theme === 'dark' ? '#0b0d10' : '#ffffff');
  };

  const doc = document as Document & {
    startViewTransition?: (callback: () => void) => { finished: Promise<void> };
  };

  if (!animate || reducedMotion.matches || typeof doc.startViewTransition !== 'function') {
    commit();
    return;
  }

  doc.startViewTransition(commit).finished.catch(() => undefined);
}

export function setMode(next: ThemeMode, options: { animate?: boolean } = {}): void {
  currentMode = next;
  try {
    localStorage.setItem(STORAGE_KEY, next);
  } catch {
    // Non-fatal: the session still themes correctly, it just will not persist.
  }
  applyTheme(resolveMode(next), options.animate ?? true);
}

export const getMode = (): ThemeMode => currentMode;

media.addEventListener('change', () => {
  if (currentMode === 'system') applyTheme(resolveMode('system'), false);
});

// Long-lived tabs drift from the OS setting; re-sync on focus instead of polling.
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible' && currentMode === 'system') {
    applyTheme(resolveMode('system'), false);
  }
});

4. The cascade scaffolding

@layer tokens, base, components, utilities;

:root {
  color-scheme: light dark; /* fixes native scrollbars, form controls, and canvas */
}

/* Component-scoped token: not inherited, so style recalc does not
   propagate it to every descendant. Trade-off: consumers must
   reference it from an element inside the component's own subtree. */
@property --card-bg {
  syntax: '<color>';
  inherits: false;
  initial-value: transparent;
}

/* Every theme change repaints text; never transition the whole tree. */
@media (prefers-reduced-motion: no-preference) {
  ::view-transition-old(root),
  ::view-transition-new(root) {
    animation-duration: 220ms;
  }
}

Performance Benchmarks & Trade-Offs

Measured on a Pixel 4a (Chrome 124, 4x CPU throttle off), 12,400-element product page, 40 Lighthouse CI runs per row. Theme swap = toggling data-theme on <html> and reading the next long frame.

| Strategy | Custom props on root | Total CSS (gzip) | Theme swap p50 / p99 | Rebrand effort | Build step | |---|---|---|---|---|---| | Raw hex in components, duplicated per theme | 0 | 41.2 KB | 26.0 ms / 58.0 ms | 34 components | none | | Runtime CSS-in-JS theme object | 0 | 38.4 KB | 21.6 ms / 47.0 ms | 1 provider | none | | Primitives only as CSS vars | 412 | 14.1 KB | 6.1 ms / 12.9 ms | edit primitive ramp | 0.4 s | | Primitives + semantics | 626 | 11.8 KB | 6.8 ms / 14.2 ms | edit semantic roles | 0.9 s | | Primitives + semantics + component tokens | 984 | 13.4 KB | 9.3 ms / 19.8 ms | edit component tokens | 1.2 s | | Primitives + semantics, inherits: false on 60% | 626 | 11.8 KB | 4.1 ms / 9.6 ms | edit semantic roles | 0.9 s |

The counterintuitive result: the primitive-only row is faster than the three-tier row. More custom properties on :root means more inherited-property work per element during style recalc - 984 props x 12,400 nodes is 12.2M property registrations. That is the real cost of granularity, and it is why component tokens belong in component CSS, not on :root.

| Typography strategy | Distinct sizes | Fluid | CLS incidents (40 templates) | Unexplained drift | Config LOC | |---|---|---|---|---|---| | Ad-hoc px lifted from Figma | 63 | no | 11 | +/-9% | 0 | | Static modular, r = 1.125 | 9 | no | 3 | 0% | 24 | | Static modular, r = 1.25 | 9 | no | 0 | 0% | 24 | | Fluid modular, 1.2 to 1.25 | 9 | yes | 0 | 0% | 61 | | Fluid dual-ratio with clamp bands | 9 | yes | 0 | 0% | 88 |

Pro-Tips & Common Pitfalls

  • Never emit component tokens on `:root`. Each one is inherited by every node. Scope them with @property { inherits: false } or move them into the component's layer. Measured saving: 40% off p50 style recalc.
  • **Never do *, *::before, *::after { transition: background-color 200ms }.** A theme toggle then paints 12,400 elements twice. Use the View Transitions API for a root cross-fade, or accept an instant swap.
  • Never use `#000` or `#fff` in a dark theme. Pure black kills elevation cues and halates on OLED; pure white text vibrates on dark surfaces. Floor at oklch(14.5% ...) and ceiling at oklch(96% ...).
  • Never derive dark colors by HSL or RGB inversion. Hue shifts by 10-25 degrees and 34% of your text pairings fail WCAG AA. Move lightness in OKLCH, hold hue constant.
  • Forbid dashes inside token path segments. color.action.bg and color.action-bg collide on --color-action-bg and one silently wins.
  • Always run cycle detection. A two-node alias loop in JSON passes schema validation and then resolves to garbage or infinite-loops depending on your tooling.
  • Always set `color-scheme`. Without it, native scrollbars, <input> chrome, and <select> dropdowns stay light on a dark page - a defect no CSS variable can fix.
  • Guard against FOUC with an inline `<head>` script under 1 KB, plus a server-rendered data-theme from a cookie for SSR. A useEffect-based theme hook always flashes.
  • Do not trust `prefers-color-scheme` alone. Persist an explicit tri-state (light, dark, system) and re-sync on visibilitychange; OS themes change while tabs are backgrounded.
  • Use `rem` for spacing and type, `px` only for hairlines and border widths. At 200% zoom, a px-based layout breaks while text doubles.
  • Lint contrast on token pairs, not on pages. Automate APCA Lc >= 75 for every color.text.* x color.surface.* combination in both themes; catching this in CI is 30 lines of code versus a two-week accessibility remediation.
  • Watch for out-of-gamut `oklch()`. Wide-chroma accents render differently per engine unless you clamp chroma at build time.

Frequently Asked Questions (FAQ)

What is the difference between primitive and semantic design tokens?

Primitive tokens are raw, theme-agnostic values named by material family - color.blue.500, dimension.space.4 - and they never encode intent. Semantic tokens are role-based aliases that describe where a value is used: color.surface.base, color.text.muted, color.action.bg. The distinction matters because a theme is implemented purely as a re-pointing of the semantic alias table, so switching to dark mode changes 214 pointers rather than 1,180 values. Application code should only ever consume semantic tokens; if a component imports a primitive directly, your next rebrand becomes a full-codebase migration instead of a one-file diff.

Which modular scale ratio should I use for typography?

Use 1.125 to 1.2 for dense product UI, 1.25 for hybrid marketing and product surfaces, and 1.333 or higher only for content-led editorial layouts where the display sizes dominate. The practical constraint is the mid-scale: a ratio of 1.5 makes step +2 unusably large for anything nested inside body copy, so anything above 1.333 should be reserved for display-only steps with a tighter ratio below the breakpoint. The most robust production pattern is a dual-ratio scale - roughly 1.2 at 360 px width interpolating to 1.25 at 1440 px - expressed as clamp() with rem bounds so browser zoom and user font-size preferences still work.

How do I prevent a flash of the wrong theme (FOUC) when switching dark mode?

Write the resolved theme before first paint. Put a small inline script in <head>, before any stylesheet <link>, that reads localStorage plus matchMedia('(prefers-color-scheme: dark)') and sets data-theme and style.colorScheme on document.documentElement synchronously. For server-rendered apps, also render the data-theme attribute from a cookie so the HTML arrives already themed. The inline script costs roughly 0.3 ms of parse-blocking time and should stay under 1 KB; a React useEffect or a client-side theme provider runs after paint and will always flash. Pair this with color-scheme: light dark in CSS so native scrollbars and form controls match immediately.