Building a Multi-Theme System with CSS Custom Properties
CSS custom properties (variables) make multi-theme systems elegant and maintainable. Here is how to build one from scratch.
Define Your Token Structure
Start with semantic tokens, not raw values. Instead of --blue-500, use --color-primary, --color-surface, --color-text. This decouples your component styles from specific colors, making theme switching a matter of swapping variable values.
The Root Theme
Define your default theme on :root. This serves as the fallback and typically the light theme. Keep all color, spacing, border-radius, and shadow tokens here. Components reference these tokens exclusively.
Dark Mode With a Data Attribute
Add [data-theme="dark"] selector that overrides the color tokens. Toggle the attribute on the element with JavaScript. This is more flexible than prefers-color-scheme alone because it lets users override the system setting.
Brand Theme Extensions
For white-label products, create additional theme files that override the primary, secondary, and accent color tokens. Each brand gets its own [data-theme="brand-name"] block. The component CSS stays unchanged.
Component-Level Scoping
Some components need local theme variations. A card with a dark header on a light page can override tokens at the component level. CSS custom properties inherit through the DOM tree, so a scoped override affects all children.
Performance Notes
CSS custom properties are resolved at computed value time, not parse time. Changing a custom property triggers a repaint only for elements that use it. Theme switching with custom properties is fast — no stylesheet swapping, no flash of unstyled content. Use our CSS Gradient Generator with your theme colors to create consistent gradient patterns.
Related Posts
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.