Adding dark mode to your website enhances user experience by providing a visually comfortable alternative to the default light theme. It’s especially useful for reducing eye strain in low-light environments. Here’s a step-by-step guide to implementing dark mode:
1. Use CSS Variables for Theming
- Define Light and Dark Themes:
- Use CSS variables to define colors for both themes.
:root {
--background-color: #ffffff;
--text-color: #000000;
}
[data-theme="dark"] {
--background-color: #121212;
--text-color: #ffffff;
}
- Apply Variables:
body {
background-color: var(--background-color);
color: var(--text-color);
}
2. Toggle Dark Mode with JavaScript
- Add a Toggle Button:
<button id="theme-toggle">Toggle Dark Mode</button>
- JavaScript to Switch Themes:
const toggleButton = document.getElementById('theme-toggle');
const currentTheme = localStorage.getItem('theme');
if (currentTheme === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
}
toggleButton.addEventListener('click', () => {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
document.documentElement.setAttribute('data-theme', isDark ? 'light' : 'dark');
localStorage.setItem('theme', isDark ? 'light' : 'dark');
});
3. Respect System Preferences
- Use
prefers-color-scheme
Media Query: - Automatically apply dark mode if the user’s system preference is set to dark.
@media (prefers-color-scheme: dark) {
:root {
--background-color: #121212;
--text-color: #ffffff;
}
}
4. Save User Preference
- Use
localStorage
: - Save the user’s theme preference in
localStorage
to persist across sessions.
const currentTheme = localStorage.getItem('theme');
if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);
}
5. Test and Optimize
- Check Contrast and Readability:
- Ensure text and background colors meet accessibility standards (e.g., WCAG).
- Test on Multiple Devices:
- Verify dark mode works well on different screen sizes and browsers.
Key Takeaways
- Use CSS variables for easy theme switching.
- Add a toggle button for manual dark mode control.
- Respect system preferences with
prefers-color-scheme
. - Save user preferences using
localStorage
.
By following these steps, you can create a seamless dark mode experience for your website users.