CSS ยท Chapter 40 of 44

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.

Syntax
: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.

Example 1 (css)
:root {
  --bg: #ffffff;
  --text: #111111;
}
[data-theme="dark"] {
  --bg: #111111;
  --text: #ffffff;
}
body {
  background: var(--bg);
  color: var(--text);
}
Output
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.
๐Ÿ’ก Note: This pattern is the basis of most modern dark-mode implementations.

๐Ÿ“ Quick Quiz

1. What is a common way to implement theme switching with CSS variables?

2. Where should components get their colors from in this pattern?

3. What can toggle the active theme at runtime?