Skip to content

Lesson 27 of 52Modern CSS

CSS Architecture for Design Systems

Build the plain-CSS layer under a design system: token tiers, multi-brand theming, oklch colour maths, @layer, @property, @scope and container queries.

22 min read0/4 questions

Your company has three products, two brands after an acquisition, a web app, a marketing site built by an agency, and native iOS and Android apps. Design wants one button. Today there are fourteen, each with a slightly different blue, and changing the brand colour means a two-week hunt through repositories. A design system fixes that, and underneath every design system, whatever framework sits on top, is a layer of plain CSS: tokens, themes, layers and component styles that any team can consume without fighting the cascade. This lesson builds that layer, picking up where CSS Architecture left off. It goes deeper than the rest of this unit and assumes you have worked on a shared codebase, so skip it on a first pass if you have not. Later, Tailwind Design Systems shows how Tailwind's @theme exposes tokens, and Designing Component APIs and Design Systems in the React course covers props, variants and Storybook. Here you work one level below both.

Token tiers, and the one rule that makes them work

CSS Variables and Theming introduced three tiers of tokens: primitive, semantic and component. In a real system the tiers are not a naming nicety. They are a dependency rule.

Who may reference whom
Primitives: --blue-600, --space-4Primitives--blue-600, --space-4Semantic: --color-actionSemantic--color-actionComponent: --button-bgComponent--button-bgTheme scopes: [data-brand], darkTheme scopes[data-brand], darkComponent CSS: .button { ... }Component CSS.button { ... }points atreassignsdefaults toreadsnever

Primitives are the palette and scales: every blue, every gray, every spacing step. They say what a value is and never change between themes.

1/5

Enforce the rule with tooling, not willpower. A Stylelint rule that rejects var(--blue-*) inside component files, or a build step that only exports semantic tokens to product teams, catches violations in review.

The source of truth: design tokens as data

Tokens should not start life in CSS. They start as data that design tools and build scripts both read, then get compiled into CSS custom properties for the web, Swift for iOS and Kotlin or XML for Android. The W3C Design Tokens Community Group publishes a format for this. Its first stable version, 2025.10, was released in October 2025, and tools such as Figma plugins, Tokens Studio and Style Dictionary use it.

tokens/color.tokens.json
{
  "color": {
    "blue-600": {
      "$type": "color",
      "$value": { "colorSpace": "oklch", "components": [0.55, 0.2, 262] }
    },
    "action": {
      "$type": "color",
      "$value": "{color.blue-600}",
      "$description": "Primary buttons and links"
    }
  }
}

Keys starting with $ are reserved by the format. $value with curly braces, like {color.blue-600}, is an alias: the semantic token points at the primitive, exactly the tier rule from above. Style Dictionary reads files like this and generates every platform from one source:

style-dictionary.config.mjs
export default {
  source: ["tokens/**/*.tokens.json"],
  platforms: {
    css: {
      transformGroup: "css",
      buildPath: "dist/css/",
      files: [{ destination: "tokens.css", format: "css/variables" }],
    },
    ios: {
      transformGroup: "ios-swift",
      buildPath: "dist/ios/",
      files: [{ destination: "Tokens.swift", format: "ios-swift/class.swift" }],
    },
  },
};

Style Dictionary has read the format's $value and $type keys since version 4. Support for every detail of the 2025.10 version (such as the structured colour objects) was still being completed at the time of writing, so check its docs for your version before you rely on them.

Theming: light-dark(), brands and density

With semantic tokens in place, a theme is a scope that reassigns them. Three dimensions usually vary independently: colour scheme, brand and density. Model each as its own attribute so they combine freely.

light-dark(a, b) returns a or b depending on the element's used color-scheme. It only works if you set color-scheme, and it has been Baseline since May 2024. One declaration now covers both schemes, so you no longer duplicate every token in a media query. Setting color-scheme: light dark follows the OS; setting color-scheme: dark on a scope forces dark there.

The demo below has all three dimensions. Try every combination.

HTML & CSS
<style> /* Tier 1: primitives */ :root { --blue-300: oklch(0.78 0.11 255); --blue-600: oklch(0.55 0.2 262); --green-300: oklch(0.82 0.12 160); --green-700: oklch(0.45 0.11 160); --gray-50: oklch(0.985 0 none); --gray-200: oklch(0.9 0.01 265); --gray-400: oklch(0.72 0.02 265); --gray-500: oklch(0.5 0.02 265); --gray-700: oklch(0.38 0.02 265); --gray-800: oklch(0.28 0.02 265); --gray-900: oklch(0.2 0.02 265); --space-1: 4px; --space-2: 8px; --space-3: 12px; --space-4: 16px; --space-6: 24px; } /* Tier 2: semantic tokens. Themes only touch this tier. */ .app { color-scheme: light; --color-surface: light-dark(var(--gray-50), var(--gray-900)); --color-raised: light-dark(white, var(--gray-800)); --color-text: light-dark(var(--gray-900), oklch(0.95 0.01 265)); --color-muted: light-dark(var(--gray-500), var(--gray-400)); --color-border: light-dark(var(--gray-200), var(--gray-700)); --color-action: light-dark(var(--blue-600), var(--blue-300)); --color-on-action: light-dark(white, var(--gray-900)); --space-inset: var(--space-6); --space-gap: var(--space-3); } .app[data-scheme="dark"] { color-scheme: dark; } .app[data-brand="green"] { --color-action: light-dark(var(--green-700), var(--green-300)); } .app[data-density="compact"] { --space-inset: var(--space-3); --space-gap: var(--space-1); } /* Tier 3: component tokens, defaulting to semantic ones */ .button { --button-bg: var(--color-action); --button-fg: var(--color-on-action); --button-hover: color-mix(in oklch, var(--button-bg), var(--color-text) 18%); --button-disabled: color-mix(in oklch, var(--button-bg) 35%, var(--color-surface)); background: var(--button-bg); color: var(--button-fg); border: 0; padding: var(--space-gap) var(--space-inset); font: inherit; cursor: pointer; } .button:hover { background: var(--button-hover); } .button:disabled { background: var(--button-disabled); cursor: not-allowed; } .button.subtle { background: oklch(from var(--button-bg) l c h / 0.14); color: var(--color-text); } .app { background: var(--color-surface); color: var(--color-text); padding: var(--space-inset); } .card { background: var(--color-raised); border: 1px solid var(--color-border); padding: var(--space-inset); display: grid; gap: var(--space-gap); } .card p { margin: 0; color: var(--color-muted); } .row { display: flex; gap: var(--space-2); flex-wrap: wrap; } .controls { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; }</style><div class="controls"> <label>Scheme <select data-attr="scheme"><option>light</option><option>dark</option></select></label> <label>Brand <select data-attr="brand"><option>blue</option><option>green</option></select></label> <label>Density <select data-attr="density"><option>comfortable</option><option>compact</option></select></label></div><div class="app"> <div class="card"> <strong>Upgrade to Pro</strong> <p>Unlimited projects and priority support.</p> <div class="row"> <button class="button">Upgrade</button> <button class="button subtle">Compare plans</button> <button class="button" disabled>Unavailable</button> </div> </div></div><script> const app = document.querySelector(".app"); document.querySelectorAll("select").forEach((s) => { s.onchange = () => { app.dataset[s.dataset.attr] = s.value; }; });</script>

Preview

Notice what you did not write: no dark versions of the hover colour, no green version of the disabled colour. The component derives those states from whatever --button-bg resolves to. Change --green-700 to a red and every state follows.

Where derived tokens resolve

One subtle trap catches teams. The browser substitutes var() inside a custom property on the element that declares it, and descendants inherit the result. If you declared --button-hover: color-mix(in oklch, var(--color-action) ...) on :root, it would be computed once with the root's blue. A [data-brand="green"] scope further down changes --color-action, but --button-hover was already computed and inherited as blue. Hover states would stay on the old brand.

The fix is the one in the demo: declare derived tokens on the component, so they are computed where the current theme is visible. As a rule, put raw values on :root and scopes, and put anything containing var() that depends on themeable tokens on the element that uses it.

Colour maths with oklch

Hex and HSL are poor for design systems because their lightness is not perceptual: HSL yellow and HSL blue at 50% lightness look wildly different. OKLCH has three channels: L (perceived lightness, 0 to 1), C (chroma, roughly saturation) and H (hue angle). Equal steps of L look like equal steps of lightness across hues, so a palette built by stepping L is consistent, and predicted contrast tracks reality much better. oklch() and color-mix() are both Baseline Widely available.

Two functions generate states from a base colour:

  • color-mix(in oklch, A, B 20%) mixes 80% A with 20% B. Mixing toward the text colour gives a hover that darkens in light mode and lightens in dark mode automatically, as in the demo.
  • Watch neutral colours in mixes. A gray written as oklch(0.985 0 0) has a hue of 0, which is red, and mixing it with blue in OKLCH swings the hue through pink. Write achromatic primitives with a hue of none, as the demo's --gray-50 does, and the mix keeps the other colour's hue.
  • Relative colour syntax takes an origin colour and rewrites its channels: oklch(from var(--brand) calc(l - 0.08) c h) is the brand 0.08 darker, and oklch(from var(--brand) l c h / 0.14) is the brand at 14% opacity. It became Baseline Newly available in September 2024, so treat it as an enhancement if you support older Safari, with a color-mix() fallback first.
Predict the outputHTML & CSS

What is the lightness (L) of the resulting colour? Type the number.

--brand: oklch(0.6 0.15 250);
--brand-hover: oklch(from var(--brand) calc(l + 0.1) c h);
Need a nudge? Hints walk you through it.

Generated colours still need contrast checks

Maths makes states consistent, not accessible. Every foreground and background pair your semantic tokens can produce, in every theme and brand, must meet WCAG contrast: 4.5 to 1 for body text, 3 to 1 for large text and UI component boundaries. Teams run this as a test in the token build. Here is a self-contained version that converts OKLCH to sRGB and computes the WCAG ratio.

JavaScript
// Convert an OKLCH colour to linear sRGB (0 to 1), clipping out-of-gamut values.function oklchToLinearSrgb([l, c, h]) { const hr = (h * Math.PI) / 180; const a = c * Math.cos(hr), b = c * Math.sin(hr); const l_ = l + 0.3963377774 * a + 0.2158037573 * b; const m_ = l - 0.1055613458 * a - 0.0638541728 * b; const s_ = l - 0.0894841775 * a - 1.291485548 * b; const [L, M, S] = [l_ ** 3, m_ ** 3, s_ ** 3]; return [ 4.0767416621 * L - 3.3077115913 * M + 0.2309699292 * S, -1.2684380046 * L + 2.6097574011 * M - 0.3413193965 * S, -0.0041960863 * L - 0.7034186147 * M + 1.707614701 * S, ].map((v) => Math.min(1, Math.max(0, v)));} // WCAG 2 relative luminance uses linear RGB, so no gamma step is needed here.function luminance([r, g, b]) { return 0.2126 * r + 0.7152 * g + 0.0722 * b;}function contrast(fg, bg) { const a = luminance(oklchToLinearSrgb(fg)); const b = luminance(oklchToLinearSrgb(bg)); return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);} const themes = { light: { text: [0.2, 0.02, 265], surface: [0.985, 0, 0], muted: [0.5, 0.02, 265], action: [0.55, 0.2, 262], onAction: [1, 0, 0] }, dark: { text: [0.95, 0.01, 265], surface: [0.2, 0.02, 265], muted: [0.72, 0.02, 265], action: [0.78, 0.11, 255], onAction: [0.2, 0.02, 265] }, "orange brand": { text: [0.2, 0.02, 265], surface: [0.985, 0, 0], muted: [0.5, 0.02, 265], action: [0.7, 0.17, 50], onAction: [1, 0, 0] },};const pairs = [["text", "surface", 4.5], ["muted", "surface", 4.5], ["onAction", "action", 4.5]]; const rows = [];for (const [theme, t] of Object.entries(themes)) { for (const [fg, bg, min] of pairs) { const ratio = contrast(t[fg], t[bg]); rows.push({ theme, pair: `${fg} on ${bg}`, ratio: ratio.toFixed(2), pass: ratio >= min ? "yes" : "NO" }); }}console.table(rows);const failing = rows.filter((r) => r.pass === "NO");console.log(failing.length ? `${failing.length} pair(s) fail. Fix the tokens before release.` : "All pairs pass.");
Output
Press Run (⌘ Enter) to see what happens.

The orange brand fails: white text on a bright orange gives about 2.8 to 1. That is common with yellow, orange and green brands. Lower the orange's L to around 0.55, or switch onAction to the dark gray for that brand, and run it again. In CI, the same check fails the build instead of printing a table.

@layer: a library that is easy to override

Modern CSS Features showed how cascade layers order styles. For a library, layers solve the oldest complaint about design systems: "I had to use !important to change your button." Ship your CSS inside named layers, in a fixed order:

ds.css
@layer reset, tokens, base, components, utilities, overrides;
 
@layer tokens { :root { --color-action: oklch(0.55 0.2 262); } }
@layer components {
  .ds-card .ds-card-title { font-size: 1.25rem; color: var(--color-text); }
}

Two properties of layers make this work for consumers. First, unlayered CSS beats every layer, so an application's plain .promo-title { color: crimson } wins over the library's two-class selector without any specificity war. Second, layer order is fixed by the first time a name appears, so the library's opening @layer statement locks its internal order no matter how the files are split or loaded. Leaving an empty overrides layer at the end gives consumers a sanctioned place for deliberate changes when their own app uses layers too.

Consumers can also put a whole third-party stylesheet into a layer they choose: @import url("vendor.css") layer(vendor);. Declare vendor early in your own order and nothing in that file can beat your components, whatever selectors it uses.

One warning: !important reverses layer order. An important declaration in an early layer beats an important one in a later layer. That is designed so a reset can protect accessibility rules, but it surprises people who reach for !important to fix a layer problem.

How a consumer's CSS meets the library's layers
  1. App CSS, unlayered.promo-title { color: crimson }
  2. @layer overridesempty, reserved for consumers
  3. @layer utilities.ds-mt-4
  4. @layer components.ds-card .ds-card-title
  5. @layer base, tokens, resetelement defaults and variables

The library's component rule has a specificity of two classes. Without layers, a consumer would need a stronger selector to beat it.

1/3
Quick check
Your library ships @layer components { .ds-nav a.active { color: navy } }. A product team writes .nav-link { color: teal } in their own unlayered stylesheet. Which colour wins on an active link that has both classes?
Need a nudge? A hint rules out a wrong answer.

@property: typed tokens

A normal custom property is just a token string. The browser cannot animate it (it does not know --angle is an angle) and cannot validate it. @property registers a custom property with a type:

HTML & CSS
<style> @property --angle { syntax: "<angle>"; inherits: false; initial-value: 0deg; } @property --brand { syntax: "<color>"; inherits: true; initial-value: rebeccapurple; } .ring { width: 110px; aspect-ratio: 1; border-radius: 50%; background: conic-gradient(from var(--angle), var(--brand), #f59e0b, var(--brand)); } @media (prefers-reduced-motion: no-preference) { .ring { animation: spin 3s linear infinite; } } @keyframes spin { to { --angle: 360deg; } } .typed { --brand: bananas; color: var(--brand); font-weight: bold; } .untyped { --plain: bananas; color: var(--plain); font-weight: bold; }</style><div class="ring"></div><p class="typed">Typed: an invalid value gives the registered initial colour.</p><p class="untyped">Untyped: an invalid value silently becomes unset (inherited black).</p>

Preview

Two benefits show here. The conic gradient animates smoothly because the browser can interpolate an <angle>; without registration, --angle would jump from start to end. And when someone assigns bananas to the typed --brand, the browser falls back to the registered initial-value instead of quietly unsetting the colour. Registered properties are also cheaper when inherits: false, because the browser does not pass them down the tree. @property has been Baseline since July 2024.

Component styling APIs: custom properties, @scope and container queries

A component's public styling API should be a small set of documented custom properties, not "override any class you find". Consumers write .pricing .ds-card { --card-padding: 32px; } and you keep the freedom to rename every internal class. Prefix private ones (--_shadow) so everyone knows they are not part of the contract, and treat renaming a public one as a breaking change.

Two features finish the job.

@scope limits where selectors match. @scope (.card) to (.card-content) styles everything inside a card except what is inside its content slot, a "donut" that BEM naming could only approximate. A p rule for the card's footer no longer leaks into a paragraph a consumer puts in the slot. Proximity also helps: when scopes nest, the closer scope root wins a tie. @scope shipped in Firefox 146 in December 2025, reaching Baseline Newly available in early 2026, so check your policy before relying on it.

Container queries make components respond to the space they are given, not the viewport. The same card can sit in a narrow sidebar and a wide main column on one page. Size container queries are Baseline Widely available.

HTML & CSS
<style> @scope (.card) to (.card-content) { :scope { container-type: inline-size; border: 1px solid #d4d4d8; padding: var(--card-padding, 16px); margin-bottom: 12px; } p { margin: 0; color: #71717a; font-size: 14px; } .media { background: #c7d2fe; min-height: 70px; } } .layout { display: grid; gap: 12px; } @container (min-width: 260px) { .layout { grid-template-columns: 130px 1fr; } }</style><div style="display: grid; grid-template-columns: 220px 1fr; gap: 12px;"> <article class="card"> <div class="layout"> <div class="media"></div> <div> <p>Card chrome text (scoped)</p> <div class="card-content"><p>Consumer paragraph: not grey, because it is in the donut hole.</p></div> </div> </div> </article> <article class="card" style="--card-padding: 24px"> <div class="layout"> <div class="media"></div> <div> <p>Card chrome text (scoped)</p> <div class="card-content"><p>Same component, wider container, side-by-side layout.</p></div> </div> </div> </article></div>

Preview

The left card is narrow, so it stacks. The right card's content box is wider than 260px, so the same markup lays out side by side. The consumer's paragraphs inside .card-content keep their normal colour, and the second card changes its padding through the public --card-padding property.

Match the pairs0/5 matched

Match each CSS feature to the design-system problem it solves.

Choose an item, then its match on the other side.

Fluid type and space scales

Instead of jumping font sizes at breakpoints, many systems define a fluid scale: each step grows smoothly between a minimum at a small viewport and a maximum at a large one, using clamp(). Tools such as Utopia generate these.

:root {
  /* 16px at a 320px viewport, growing to 20px at 1240px */
  --step-0: clamp(1rem, 0.913rem + 0.435vw, 1.25rem);
  /* 19.2px to 25px: a 1.2 ratio on small screens, 1.25 on large */
  --step-1: clamp(1.2rem, 1.074rem + 0.63vw, 1.5625rem);
  --step-2: clamp(1.44rem, 1.262rem + 0.892vw, 1.953rem);
  --space-m: clamp(1rem, 0.87rem + 0.65vw, 1.375rem);
}

The middle value mixes rem and vw on purpose. A pure vw size does not grow when the user zooms the text, which fails WCAG's resize text requirement. Keeping a rem part means zoom still works. Generate the numbers with a tool rather than by hand, and expose only the steps (--step-0, --step-1) as tokens.

Governance: tokens are an API

Once fifty teams consume your tokens, a token is a public API. Designing Component APIs and Design Systems, in the React course, covers versioning and deprecating component props; tokens need the same discipline.

Put it in order5 steps

Put the steps for retiring the semantic token --color-brand in favour of --color-action in a safe order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Publish the CSS as a versioned package, follow semantic versioning (renaming or removing a token is a major change; adding one is a minor change), and keep a visual regression suite of every component in every theme, so a token change that shifts a colour shows up as a screenshot diff in review.

Key terms
semantic token
A token named for its purpose, such as --color-action, that points at a primitive and is reassigned by themes.
DTCG format
The W3C Design Tokens Community Group's JSON format for tokens, with $value, $type and {alias} references. Stable since 2025.10.
light-dark()
A CSS function that returns its first value in a light colour scheme and its second in a dark one. Requires color-scheme.
OKLCH
A perceptual colour space with lightness, chroma and hue, so equal lightness steps look equal across hues.
relative colour syntax
Deriving a colour from another by rewriting its channels, as in oklch(from var(--brand) calc(l - 0.1) c h).
@property
Registers a custom property with a type, inheritance and initial value, so it can animate and fall back safely.
@scope
Limits selectors to a subtree, optionally with a lower boundary that creates a donut-shaped scope.