Runtime Theme Switching
You'll learn how to dynamically change your site's theme on the fly using JavaScript to update CSS custom properties, without ever touching a stylesheet.
The Core Idea
Runtime theme switching means letting users change themes instantly—light to dark, brand A to brand B—by modifying CSS custom property values with JavaScript. Since custom properties (CSS variables) cascade through your entire stylesheet, updating just a few root-level variables can instantly repaint your entire interface. No CSS file recompilation, no page reload required.
Think of it like changing the ink cartridges in a printer while it's running—the template (your CSS rules) stays the same, but the colors flowing through it change immediately.
How It Works
You've already defined theme tokens as custom properties (from previous lessons). Now you use JavaScript to swap their values at runtime:
:root {
--color-primary: #3b82f6;
--color-background: #ffffff;
--color-text: #1f2937;
}
function switchToDarkTheme() {
const root = document.documentElement;
root.style.setProperty('--color-primary', '#60a5fa');
root.style.setProperty('--color-background', '#1f2937');
root.style.setProperty('--color-text', '#f9fafb');
}
When switchToDarkTheme() runs, every element using var(--color-background) or var(--color-text) instantly reflects the new values. The browser repaints automatically—no CSS parsing overhead, just value substitution.
You can trigger this from a toggle button, user preference detection, or time-of-day logic. Store the choice in localStorage to persist across sessions.
Key Takeaway:
Runtime theme switching uses JavaScript's setProperty() to modify CSS custom property values on the fly, enabling instant, zero-recompilation theme changes across your entire interface.