WeCodeAcademy

Step 5: A dark mode switch

Because every colour is a variable, dark mode is just a second set of values. Add a dark class to the body that redefines --bg, --fg, --card and --accent, then a small script toggles the class when a button is clicked. The button uses aria-pressed so assistive technology knows its state.

Examplehtml
Open in editor »

In a finished site you would also remember the choice in localStorage and start from the visitor's system preference with window.matchMedia('(prefers-color-scheme: dark)').

Your turn: write the code

Write nextTheme(current) that returns "dark" when the current theme is "light" and "light" otherwise. Print nextTheme("light") and nextTheme("dark").

Quick check

Why are the colours stored in CSS variables?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.