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.
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.
Primitives are the palette and scales: every blue, every gray, every spacing step. They say what a value is and never change between themes.
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.
{
"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:
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.
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 ofnone, as the demo's--gray-50does, 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, andoklch(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 acolor-mix()fallback first.
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);
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.
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:
@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.
The library's component rule has a specificity of two classes. Without layers, a consumer would need a stronger selector to beat it.
@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?@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:
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.
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 each CSS feature to the design-system problem it solves.
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 the steps for retiring the semantic token --color-brand in favour of --color-action in a safe order.
- Tap the steps below in the right order.
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.
- 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,$typeand{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.