Lesson 5 of 8

Dark mode

Goal

Swap variables instead of repeating colors

01

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"]).

02

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
  1. The page takes its colors from --bg and --fg
  2. A prefers-color-scheme: dark query redefines --bg
  3. Choosing “Dark” makes the page dark even when the system is light
  4. The card turns dark along with the page
  5. Choosing “Light” wins over a dark system
  6. color-scheme follows the theme
03

Hints

0/3
Track lessons0 of 8 done

Learn page layout, form validation, motion and accessibility: the things that make an interface comfortable to use in real life, not just nice to look at.

Advanced level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Learn page layout, form validation, motion and accessibility: the things that make an interface comfortable to use in real life, not just nice to look at.

Advanced level, 8 lessons, 2 hours in total.