Implementing Dark Mode: Best Practices for Modern Web Apps
A comprehensive guide to implementing dark mode that respects user preferences and provides a great experience.
Emily Zhang
Frontend Engineer
Why Dark Mode Matters
Dark mode has become more than a trend—it’s an accessibility feature that many users depend on. Here’s why it matters:
- Reduces eye strain in low-light conditions
- Can extend battery life on OLED screens
- Provides a preferred aesthetic for many users
- Shows attention to user experience
Implementation Strategies
CSS Custom Properties
The foundation of a good dark mode implementation is CSS custom properties:
:root {
--color-background: #ffffff;
--color-text: #1a1a1a;
--color-primary: #3b82f6;
}
.dark {
--color-background: #0a0a0a;
--color-text: #fafafa;
--color-primary: #60a5fa;
}
Respecting System Preferences
Always start by respecting the user’s system preference:
// Check system preference
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// Apply initial theme
if (prefersDark) {
document.documentElement.classList.add('dark');
}
Color Considerations
When designing for dark mode, don’t simply invert colors. Consider:
- Reduce contrast - Pure white on pure black is harsh
- Adjust saturation - Colors may need to be desaturated
- Mind the shadows - Dark mode shadows work differently
- Test accessibility - Ensure WCAG compliance
Recommended Color Palette
| Element | Light Mode | Dark Mode |
|---|---|---|
| Background | #ffffff | #0f172a |
| Text | #1e293b | #e2e8f0 |
| Primary | #3b82f6 | #60a5fa |
| Muted | #94a3b8 | #64748b |
Avoiding Flash of Incorrect Theme
One common issue is the “flash” when the page loads with the wrong theme. Prevent this with:
<script>
// Run before page renders
const theme = localStorage.getItem('theme') ||
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.classList.toggle('dark', theme === 'dark');
</script>
Testing Your Implementation
Make sure to test:
- Both light and dark modes
- Theme switching without page reload
- System preference changes
- Persistence across sessions
- All UI components in both modes
Conclusion
A well-implemented dark mode shows users you care about their experience. Take the time to do it right, and your users will appreciate it.