← Lessons

quiz vs the machine

Silver1100

Frontend

The Theming and Dark Mode

Swap whole color schemes at runtime without rewriting components.

4 min read · intro · beat Silver to climb

How theming works

Theming means components read abstract variables instead of fixed colors, and a theme supplies the concrete values. To switch to dark mode you change the variables, not the components.

  • Define colors as CSS custom properties on a root element
  • Components reference variables like color background and color text
  • A data theme attribute or class on the html element selects the active set

Respecting the user

Good dark mode follows the system but lets the user override it.

  • Read the prefers color scheme media query for the default
  • Store an explicit choice so it survives reloads
  • Apply the theme before first paint to avoid a bright flash

Theme switch flow

Beyond two themes

Because components only know variable names, the same approach supports high contrast modes or per brand themes by shipping extra variable sets.

Key idea

Make components read theme variables rather than literal colors so switching to dark mode or any theme is a single attribute change applied before first paint.

Check yourself

Answer to earn rating on the learn ladder.

1. Why should the theme be applied before first paint?

2. What lets the same components support both light and dark themes?