CSS Custom Properties for Theming
CSS variables combined with classes or attributes make it easy to build light/dark themes by swapping variable values instead of rewriting every rule.
A common pattern defines base variables on :root and overrides them inside a [data-theme="dark"] selector or similar.
:root { --bg: white; }
[data-theme="dark"] { --bg: black; }Theme switching pattern
Define default variables on :root, then override the same variable names inside a theme-specific selector like .dark-theme or [data-theme='dark'].
Why this scales well
Because components reference var(--bg-color) etc., changing the active theme class updates the entire site without touching individual component styles.
:root {
--bg: #ffffff;
--text: #111111;
}
[data-theme="dark"] {
--bg: #111111;
--text: #ffffff;
}
body {
background: var(--bg);
color: var(--text);
}The page background and text colors flip when data-theme is set to 'dark'Overriding the same variable names in a theme selector swaps colors across the whole page.
Key points
- Variables enable easy theme switching without duplicating rules.
- Override the same variable names inside a theme-scoped selector.
- Components should reference variables, not hardcoded values.
- JavaScript can toggle the theme attribute/class to switch live.
