Add a Dark Mode

In the last lesson, Animate Cheaply and Respect Reduced Motion, the garden’s cards and badges learned to keep still for visitors who ask for less motion. Many visitors have another setting turned on: a dark theme for their whole system. The garden’s site ignores it and shines its pale honeydew page at them anyway.

In this lesson, you’ll give the site a dark scheme that follows that setting by redefining two of its color tokens. You’ll make the sign-up form’s fields follow along and check that the text stays readable in both schemes. Start with the page’s own colors.

Redefine the Colors for Dark Mode

To switch colors, the page first needs to know what the visitor prefers. The prefers-color-scheme media feature reads the system’s theme, much as prefers-reduced-motion reads the motion setting. Its value is light or dark.

A programmer’s first instinct might be to invert the page with filter: invert(1) or to write a second, dark stylesheet. Inverting flips every pixel, so plot 7’s red tomatoes turn blue. A second stylesheet doubles the work for every future change. Dark mode is a second set of values for the same colors.

Your colors already live in custom properties, so you only need to redefine them. In style.css, add this query inside the tokens layer, after the :root rule:

Language: CSS
  @media (prefers-color-scheme: dark) {
    :root {
      --page: oklch(0.22 0.03 152.7);
      --text: oklch(0.93 0.03 152.7);
    }
  }

Both colors keep the garden’s green hue, 152.7. The page drops to a lightness of 0.22, and the text rises to 0.93. When the query matches, this :root rule wins because it comes later with the same specificity. Every var(--page) and var(--text) in the stylesheet then reads the dark value, and no other rule changes.

Emulate the setting as you did for reduced motion. Press Ctrl+Shift+P, or Cmd+Shift+P on macOS, type Rendering, and choose Show Rendering. Set Emulate CSS media feature prefers-color-scheme to prefers-color-scheme: dark.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.