← Lessons

quiz vs the machine

Gold1340

Frontend

prefers color scheme and Dark Mode

Respect the operating system theme preference with a media query.

5 min read · core · beat Gold to climb

Reading the system preference

Modern operating systems let users choose a light or dark appearance. The browser exposes that choice through the prefers color scheme media feature.

  • Wrap rules in a media query for prefers color scheme dark to apply dark styling automatically.
  • Pair it with CSS custom properties so a single block of overrides flips the whole palette.
  • Declaring the color scheme property tells the browser to also theme native widgets like scrollbars and form controls.

Adding a manual toggle

System preference is a good default, but many apps offer an explicit switch. The common pattern stores the choice and applies a data attribute or class on the root.

  • Use the media query as the default.
  • Let a stored user choice override the system value.
  • Read the preference in JavaScript with matchMedia and listen for changes so the UI updates when the OS theme switches mid session.

Start from the system signal, then allow an explicit override for full control.

Key idea

The prefers color scheme media query reflects the OS theme, and a stored user toggle can override it for an explicit choice.

Check yourself

Answer to earn rating on the learn ladder.

1. What does the prefers color scheme media feature report?

2. How can JavaScript react when the OS theme changes mid session?

3. What does setting the color scheme property help with?