Lesson 5 of 8
Dark mode
- 15 min
- 6 checks
- 3 hints
- Go to task
Goal
Swap variables instead of repeating colors
Explanation
The right way to build dark mode doesn't rewrite the colors in every rule. Instead, you turn all the colors into variables on :root, so components only ever use var(--bg) and the like. When you redefine just the variables, everything changes together.
You redefine them in two places: inside @media (prefers-color-scheme: dark) so the page follows the system setting automatically, and in :root[data-theme="dark"] for people who chose dark mode themselves. With each theme, set its color-scheme value too, so the browser colors buttons, fields and scrollbars to match.
Watch out for this problem: a user whose system is dark and who chose “Light” on your site stays stuck in dark mode, because the media query still applies to them. The fix is to exclude that choice inside the query with :root:not([data-theme="light"]).
Your task
Move the colors into the variables --bg, --fg and --surface on :root, along with color-scheme: light. Then redefine them with dark values plus color-scheme: dark in two places: inside the media query, excluding [data-theme="light"], and in :root[data-theme="dark"].
Checks
6 checks- The page takes its colors from --bg and --fg
- A prefers-color-scheme: dark query redefines --bg
- Choosing “Dark” makes the page dark even when the system is light
- The card turns dark along with the page
- Choosing “Light” wins over a dark system
- color-scheme follows the theme