Lesson 62 +10 XP

Dark Mode & prefers-color-scheme

Dark Mode & prefers-color-scheme

Respect the user's OS theme so they get light OR dark interface.

Reading the setting

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #121212;
    --text: #f5f5f5;
    --card: #1e1e1e;
  }
}
:root {
  --bg: #ffffff;
  --text: #111111;
  --card: #fafafa;
}
body {
  background: var(--bg);
  color: var(--text);
}

Order the default (light) variables first, then override inside the media query. Cascade sibling order matters, later overrides win.

The 4 core variables

--bg, --text, --card, --border. Enough for 95% of apps!

Enhance with color-scheme

color-scheme: dark makes native UI (scrollbars, forms) match:

@media (prefers-color-scheme: dark) {
  :root {
    color-scheme: dark;
  }
}

Test it

  • Toggle in devtools (rendering / emulate), switch Media: prefers-color-scheme.
  • Make sure BOTH themes pass contrast.

TL;DR

  • prefers-color-scheme reads OS light/dark setting.
  • Swap CSS variables in a media query for instant theming.
  • Add color-scheme so widgets follow.
  • Test both themes in DevTools.