CSS Custom Properties for Theming
Custom properties β the double-dash variables at the center of every modern design system β behave differently from the variables you may remember from preprocessors. They are runtime values: resolved by the cascade, inheritable, overridable per component, readable and writable from JavaScript, and animatable. That last property alone changes what is possible: a theme switch can transition the entire interface instead of snapping. This lesson covers how the cascade treats custom properties, how to structure token sets, how dark mode works with both media queries and attribute switching, and the performance and authoring pitfalls that catch experienced teams. The patterns assume a plain CSS codebase; every technique here works identically whether your build step is a bundler, a preprocessor or no tooling at all.
How the cascade actually treats custom properties
A custom property is declared like any other property, with a name beginning with two dashes, and consumed with var(). It inherits by default, so a value set on :root is visible in every descendant unless overridden β including inside shadow DOM slots and component scopes. Unlike preprocessor variables, the substitution happens at computed-value time in the browser, which means the same rule can resolve differently on different elements.
:root {
color-scheme: light dark;
--color-surface: #ffffff;
--color-surface-raised: #f8fafc;
--color-text: #0f172a;
--color-text-muted: #64748b;
--color-accent: #2563eb;
--color-danger: #dc2626;
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 1rem;
--space-4: 1.5rem;
--space-5: 2.5rem;
--radius-sm: 6px;
--radius-md: 12px;
--shadow-sm: 0 1px 2px rgb(15 23 42 / 0.06);
--shadow-md: 0 8px 24px rgb(15 23 42 / 0.08);
--font-sans: "Inter", system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, monospace;
--dur-fast: 150ms;
--dur-base: 250ms;
--ease-out: cubic-bezier(0.22, 1, 0.36, 1);
}
.button {
background: var(--color-accent);
color: #ffffff;
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-sm);
font-family: var(--font-sans);
box-shadow: var(--shadow-sm);
transition: background var(--dur-fast) var(--ease-out),
transform var(--dur-fast) var(--ease-out);
}
.button:hover { transform: translateY(-1px); }
.button:active { transform: translateY(0); }
.button[data-tone="danger"] {
--color-accent: var(--color-danger);
background: var(--color-accent);
}
.card {
background: var(--color-surface);
color: var(--color-text);
border-radius: var(--radius-md);
padding: var(--space-4);
box-shadow: var(--shadow-md);
display: grid;
gap: var(--space-3);
}
.card--compact {
--space-4: var(--space-3);
padding: var(--space-4);
}
The danger button redefines --color-accent on its own scope, and every rule inside that element picks up the new value β no duplicated background declaration beyond the one assignment. That local-override ability is the real design-system payoff: components expose custom properties as their public API, and themes or variants swap values instead of rewriting rules.
Fallbacks, invalid values and debugging
var() accepts a fallback as its second argument, used when the property is not defined or when the definition is invalid at computed-value time. The subtlety that trips people up: when a custom property resolves to something invalid for the property consuming it, the property becomes its inherited or initial value β not a previous declaration in the same rule.
.theme-banner {
color: var(--banner-text, var(--color-text, #0f172a));
background: var(--banner-bg, #eff6ff);
padding: var(--space-3, 1rem);
}
.theme-banner[hidden] {
display: none;
}
@supports (background: rgb(0 0 0 / 0.5)) {
.theme-banner {
background: var(--banner-bg, rgb(37 99 235 / 0.08));
}
}
.debug-tokens {
outline: 1px dashed var(--color-accent, red);
}
Debugging technique worth memorizing: select the element in dev tools and inspect the Computed panel's custom-property list; browsers also autocomplete var(-- in any rule, showing every in-scope token. When a token seems to vanish, check whether an ancestor redefined it inside a media query or a component class β because custom properties inherit, distant overrides are common and completely legal. Another frequent surprise: custom properties participate in the cascade like any other declaration, so two rules of equal specificity that set the same token resolve by source order, and a later import can silently change theme values you thought were stable.
Design tokens: structure before scale
A token set that grows ad hoc becomes unusable within months. The reliable structure separates layers: primitive tokens hold raw values, semantic tokens express intent, and component tokens wire semantics into specific parts of the UI.
| Layer | Example name | Example value | Changes when⦠|
|---|---|---|---|
| Primitive | --blue-600 | #2563eb | The palette is redesigned |
| Semantic | --color-accent | var(--blue-600) | Brand direction changes |
| Component | --button-bg | var(--color-accent) | A component's design changes |
| Variant | --button-bg-danger | var(--color-danger) | A tone needs its own accent |
| Theme override | [data-theme=dark] --color-surface | #0b1220 | Dark mode activates |
Rules of thumb: components consume only semantic tokens, never primitives; semantic tokens are defined once per theme; variant overrides live on the component class, not on :root. With that discipline, adding a high-contrast theme means writing one block of semantic overrides instead of editing hundreds of rules.
Dark mode with media queries and attribute switching
The media query route is zero-JavaScript: declare dark values under prefers-color-scheme: dark. The attribute route β data-theme="dark" on the root element β gives users an explicit choice and remembers it. Production systems usually combine both: the media query provides the default, and the attribute overrides it when a preference has been stored.
:root {
--bg-page: #f8fafc;
--bg-surface: #ffffff;
--text-primary: #0f172a;
--border-subtle: #e2e8f0;
}
[data-theme="dark"] {
--bg-page: #0b1220;
--bg-surface: #111a2e;
--text-primary: #e2e8f0;
--border-subtle: #24304a;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg-page: #0b1220;
--bg-surface: #111a2e;
--text-primary: #e2e8f0;
--border-subtle: #24304a;
}
}
html { background: var(--bg-page); color: var(--text-primary); }
body { transition: background-color var(--dur-base) var(--ease-out),
color var(--dur-base) var(--ease-out); }
The :root:not([data-theme="light"]) selector is the key detail: it lets an explicit light choice win over the system preference. Without it, users who prefer dark at the OS level could never force your site back to light.
Driving theme changes from JavaScript
Because custom properties are part of the style system, JavaScript can read and write them with the standard CSS Object Model APIs. The pattern below adds a theme toggle, persists the choice, and keeps the toggle button's accessible state in sync:
<button id="theme-toggle" type="button" aria-pressed="false">
<span class="theme-toggle-label">Dark mode</span>
</button>
<script>
const root = document.documentElement;
const toggle = document.querySelector('#theme-toggle');
const label = toggle.querySelector('.theme-toggle-label');
const storageKey = 'site-theme';
function resolveTheme() {
const stored = localStorage.getItem(storageKey);
if (stored === 'dark' || stored === 'light') return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
}
function applyTheme(theme) {
root.setAttribute('data-theme', theme);
const isDark = theme === 'dark';
toggle.setAttribute('aria-pressed', String(isDark));
label.textContent = isDark ? 'Light mode' : 'Dark mode';
}
applyTheme(resolveTheme());
toggle.addEventListener('click', () => {
const next = root.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
localStorage.setItem(storageKey, next);
applyTheme(next);
});
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (event) => {
if (!localStorage.getItem(storageKey)) {
applyTheme(event.matches ? 'dark' : 'light');
}
});
</script>
Two accessibility touches matter here: aria-pressed communicates the toggle state to assistive technology, and the system-preference listener only applies changes while the user has not made an explicit choice. For runtime token updates beyond theming β density sliders, accent pickers β use element.style.setProperty('--token', value), which writes an inline custom property that overrides everything above it in the cascade.
Performance, authoring and migration habits
Custom properties add a resolution step to computed values, and a pathological token graph with hundreds of chained references on thousands of nodes can show up in style-recalculation profiles. In practice, a few dozen tokens per theme is a non-issue; the fix if you hit limits is flattening β generate resolved values at build time for the hot paths while keeping the authoring model.
Authoring habits that keep a token system healthy: prefix tokens by category (--color-, --space-, --font-) so autocompletion stays useful; document each semantic token next to its declaration; avoid one-off tokens that exist for a single element; and migrate legacy hard-coded values gradually β when touching a component, replace its magic numbers with tokens rather than scheduling a risky big-bang rewrite. Custom properties reward incremental adoption better than almost any other CSS feature.
Two workflow details round out the system. First, expose tokens to design tooling by exporting the same values into Figma variables or a JSON token file, so design and engineering argue from one source instead of two parallel palettes that drift apart. Second, when a token changes meaning β say a spacing step becomes denser β grep the stylesheet for the old usage pattern before merging, because a token rename silently changes every component that consumed it, including ones nobody has opened in months. Treating tokens as a public API with the same review rigor as function signatures is what keeps a three-year-old design system from becoming a museum of abandoned values.
Common Mistakes
Consuming raw palette values inside components instead of semantic tokens
Fix: Reference --color-accent-style names so a palette change touches one declaration, not fifty components.
Assuming var() falls back when the resolved value is invalid for the consuming property
Fix: Invalid values collapse to the inherited or initial value; validate token syntax and test the fallback chain explicitly.
Declaring dark values only under prefers-color-scheme, trapping users in the OS theme
Fix: Add a data-theme attribute override plus the :root:not([data-theme=light]) guard so explicit choices win.
Animating a theme switch by toggling classes on every section
Fix: Rely on inheritance β one attribute change on the root plus a transition on background and color covers the page.
Creating a new token for every slight shade difference across components
Fix: Consolidate to a small semantic set; most components should need only surface, text, border and accent.
Rewriting an entire stylesheet to tokens in one unreviewable pull request
Fix: Convert component by component as you touch them, keeping the old values until the token mapping is verified.
Key Takeaways
- Custom properties are runtime, inherited values β overridable per scope, readable by JavaScript, and consumable through var() fallbacks.
- Structure tokens in layers: primitives, semantic intents, component wiring, and theme overrides.
- Dark mode works with zero script via prefers-color-scheme, and with user control via a data-theme attribute on the root.
- Components should expose tokens as their API; variants override tokens instead of restyling properties.
- JavaScript integration is one API surface: setAttribute for themes, style.setProperty for runtime token updates.
- Adopt tokens incrementally and flatten deep reference chains only if profiling shows real cost.