Theme switching
Learn to switch themes with variables.
Theme switching approach
Switching themes with variables is easy: you define the same variable names with different values for each theme. Whichever theme the app uses, those values take effect.
For example, --bg is white in light theme, navy in dark theme. A single data attribute or class change repaints the whole interface.
Data attribute or class
The most common method is putting a data-theme attribute on the root: <html data-theme="dark">. Then in CSS you write a separate selector for each value and redefine variables.
Example: [data-theme="dark"] { --bg: #0f172a; }. The same approach works with a class: .dark { ... }. Pick whichever feels right; both are common and work fine.
Exercise Define dark theme variables
Inside the [data-theme="dark"] selector, define two variables: --bg with value #0f172a and --text with value #e5e7eb.
Show example solution
open the selector and write both declarations inside.
Example solution:
[data-theme="dark"] {
--bg: #0f172a;
--text: #e5e7eb;
}
Test yourself
-
Which is the best approach for theme switching?
- Redefine variables based on a data-theme attribute
- Write a new stylesheet for each color
- Change every color one by one with JavaScript
- Reload the page and load a different CSS
Show answer
Redefine variables based on a data-theme attribute — Correct! Redefining variables per theme is the cleanest way.
-
Define the variable for dark theme
[data-theme="dark"] { --bg: ____; }Show answer
[data-theme="dark"] { --bg: #0f172a; } -
Match the themes
- [data-theme="light"]
- light theme selector
- [data-theme="dark"]
- dark theme selector
- --bg: #fff
- light theme value
- --bg: #0f172a
- dark theme value