Sub topic 3
Dark mode and advanced design-token techniques
Assume you know CSS selectors, the cascade, inheritance, linked stylesheets, and basic JavaScript. The examples use custom properties as design tokens: named values that represent shared design decisions.
Dark mode with `prefers-color-scheme`
The prefers-color-scheme media feature reads the user's operating-system preference. The color-scheme property tells the browser that the page supports light and dark controls, such as form fields and scrollbars.
:root {
color-scheme: light dark;
--color-bg: #ffffff;
--color-text: #111827;
}
@media (prefers-color-scheme: dark) {
:root {
--color-bg: #0b1020;
--color-text: #e5e7eb;
}
}
body {
background: var(--color-bg);
color: var(--color-text);
}A user-selected theme can override the media query with a more specific scope, such as [data-theme="dark"].
Scales with `calc()`
Derive related values from one base token. Changing the base then rescales the system consistently.
:root {
--space-base: 0.25rem;
--space-1: var(--space-base);
--space-2: calc(var(--space-base) * 2);
--space-4: calc(var(--space-base) * 4);
--text-base: 1rem;
--text-large: calc(var(--text-base) * 1.25);
}Typed and runtime tokens
Unregistered custom properties accept almost any text. @property adds syntax, inheritance behavior, and an initial value. Registered numeric properties can animate.
@property --accent-hue {
syntax: "<number>";
inherits: false;
initial-value: 220;
}
.button {
background: hsl(var(--accent-hue) 80% 50%);
transition: --accent-hue 0.3s ease;
}
.button:hover {
--accent-hue: 260;
}JavaScript can read resolved values and set an inline override.
const root = document.documentElement;
const styles = getComputedStyle(root);
console.log(styles.getPropertyValue("--color-text").trim());
root.style.setProperty("--accent-hue", "260");
root.style.removeProperty("--accent-hue");Pitfalls and debugging
A missing token can make a consuming declaration invalid at computed-value time. Use a fallback when a missing value is acceptable:
.badge {
padding: var(--badge-padding, 0.75rem);
}Inspect the element in developer tools. Check the winning declaration, inherited values, spelling, units, and whether a fallback contains a valid value. Remember that custom properties inherit unless registered with inherits: false.
> callout note > Keep semantic tokens independent from component selectors. A theme should change roles such as --color-bg, not rewrite every component rule.
Keep source data separate
For a growing system, store token values in JSON or another design-tool source, then generate CSS custom properties during the build. This keeps names and values consistent across CSS, JavaScript, and native platforms.
Exercise
Why should a dark theme override semantic tokens instead of primitive color tokens?
Show answer
Components consume semantic roles, so changing the roles switches the theme without changing component rules.