CodeBlanks Logo Icon CodeBlanks

Prefers color scheme

CSS course · Advanced · Lesson 33/52

Learn dark theme with @media (prefers-color-scheme).

prefers-color-scheme

Browsers watch the user's system preference: dark theme or light theme. In CSS you reach this preference through the @media (prefers-color-scheme: dark) query. If the user picked dark, the declarations inside this block take effect.

One stylesheet can now serve two themes. The user changes a system setting and the page adapts automatically. This is the cleanest way to support dark mode without shipping a separate dark stylesheet.

Theming with custom properties

The clean way to manage themes is to put colors as custom properties in :root. The light theme provides default values; the dark theme block overrides the same properties.

Example: :root { --bg: white; --text: black; } and @media (prefers-color-scheme: dark) { :root { --bg: #111; --text: #eee; } }. Components just use var(--bg); the theme switches automatically.

Exercise Define colors for the dark theme

Write an @media (prefers-color-scheme: dark) block. Inside it, include a :root selector that sets --bg to #111 and --text to #eee.

Show example solution
/* colors for the dark theme */
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #111;
    --text: #eee;
  }
}

Test yourself

  1. Which query fires only when dark theme is selected?

    • @media (color-scheme: dark)
    • @media (prefers-color: dark)
    • @media (prefers-color-scheme: dark)
    • @media (dark-mode: true)
    Show answer

    @media (prefers-color-scheme: dark) — Correct. prefers-color-scheme: dark fires only on the dark theme preference.

  2. Write the dark theme query

    @media (____: dark) {
      :root { --bg: #111; }
    }
    Show answer
    @media (prefers-color-scheme: dark) {
      :root { --bg: #111; }
    }
  3. Match the theme colors

    --bg: #111
    Dark theme background
    --text: #eee
    Dark theme text color
    --bg: #fff
    Light theme background
    --text: #111
    Light theme text color

All lessons in Advanced