Back to Lessons

CSS Dark Mode Theming

April 5, 2026

Dark Mode and System Preferences

Automatic theme switching with CSS media queries.

Dark Mode Implementation

:root {
  --bg: white;
  --text: #333;
}

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

html.dark {
  --bg: #121212;
  --text: #e0e0e0;
}

body {
  background: var(--bg);
  color: var(--text);
}

Theme Switching

  • Toggle class (html.dark)
  • localStorage persistence
  • System preference detection
  • Color scheme transitions