Skip to main content

Lesson 3 of 10

Dark Mode with CSS Variables

Dark mode is expected on modern websites. CSS variables make it simple - define light/dark color schemes, switch them with a class or media query, and your entire design adapts. This mini-build creates a complete light/dark theme toggle.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Dark Mode Strategy

  • Define all colors as CSS variables - Never hardcode colors in component styles
  • :root = light theme (default) - Define light colors on :root
  • [data-theme='dark'] - Override variables for dark mode on a data attribute
  • @media (prefers-color-scheme: dark) - Auto-detect user's OS dark mode preference
  • Toggle with JavaScript - document.documentElement.setAttribute('data-theme', 'dark')
  • Combine both - Detect OS preference, allow manual toggle, save preference in localStorage
  • Dark mode tips - Don't just invert colors. Use slightly muted backgrounds (#1a1a2e not #000). Reduce contrast slightly.

Mini-Build: Dark Mode Toggle

Mini-Build: Dark Mode ToggleHTML
HTML
โœ“ Valid
HTML|34 lines|โœ“ Valid syntax
UTF-8

Tip

The key dark mode insight: JavaScript only toggles ONE attribute (data-theme). ALL visual changes happen in CSS via variable overrides. This means dark mode works even without JavaScript if you use @media (prefers-color-scheme: dark) as a fallback.

Diagram
Loading diagramโ€ฆ

Implement seamless light and dark mode switching with CSS Custom Properties and media queries

Common Mistake

Using pure black (#000) for dark mode backgrounds. Pure black is harsh on the eyes and creates too much contrast. Use dark navy/gray tones like #0f0f23 or #1a1a2e. Also reduce white text to #e0e0e0 instead of #fff for comfortable reading.

Practice Task

Enhance the dark mode toggle above: (1) Save preference to localStorage, (2) Add @media (prefers-color-scheme: dark) as the default fallback, (3) Add transition: background 0.3s, color 0.3s to body for smooth switching.

Quick Quiz

Key Takeaways

  • Dark mode is expected on modern websites.
  • Define all colors as CSS variables - Never hardcode colors in component styles
  • :root = light theme (default) - Define light colors on :root
  • [data-theme='dark'] - Override variables for dark mode on a data attribute

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done