Dark Mode in CSS
Dark mode is a user interface option that uses a dark color palette to reduce eye strain and save battery life. You can implement it in CSS using media queries, custom classes, or the prefers-color-scheme
feature.
1. Auto-Detecting User Preference
CSS can automatically apply dark mode styles based on the user's system settings using the prefers-color-scheme
media query:
/* Default (Light Mode) */
body {
background: white;
color: black;
}
/* Dark Mode */
@media (prefers-color-scheme: dark) {
body {
background: #121212;
color: #e0e0e0;
}
}
2. Toggle Dark Mode with a Class
You can create a toggle switch using JavaScript by applying a .dark
class to the <body>
or <html>
tag.
/* Light Theme */
body {
background: #fff;
color: #111;
}
/* Dark Theme */
body.dark {
background: #111;
color: #eee;
}
Then toggle the class with JavaScript:
document.querySelector('#toggle-theme').addEventListener('click', () => {
document.body.classList.toggle('dark');
});
3. Using CSS Variables for Themes
Centralize your color values using variables for easy theme switching:
:root {
--bg: #ffffff;
--text: #111111;
}
.dark {
--bg: #121212;
--text: #eeeeee;
}
body {
background: var(--bg);
color: var(--text);
}
4. Best Practices
- Use enough contrast for readability.
- Provide a toggle if possible, regardless of system preference.
- Save the user's theme choice in
localStorage
. - Use variables for scalable theming.
Conclusion
Dark mode is a user-friendly and accessible feature. Whether you auto-detect or provide manual toggles, CSS gives you flexible options to implement dark themes with ease.