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.
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
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.
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
Finished this lesson?