How to implement dark mode with CSS and prefers-color-scheme

· Category: HTML & CSS

Short answer

Use prefers-color-scheme: dark to respect the system preference, and CSS custom properties to switch color palettes dynamically.

Steps

  1. Define a set of color variables for light and dark themes.
  2. Use @media (prefers-color-scheme: dark) to override values.
  3. Optionally add a manual toggle by applying a class to html.

Example

:root {
  --bg: #fff;
  --text: #111;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #111;
    --text: #fff;
  }
}

[data-theme="dark"] {
  --bg: #111;
  --text: #fff;
}

Tips

  • Store the user preference in localStorage.
  • Use color-scheme: light dark to style native form controls.
  • Test contrast ratios in both themes for accessibility.