
Dark mode is becoming increasingly popular in modern web and mobile applications. It helps reduce eye strain and save battery life, which is why many websites and apps support it. So, how can you add dark mode support to your website? In this article, we’ll show you how to easily implement theme switching using CSS and JavaScript.
1. Simple Dark Mode with CSS
The easiest way to apply dark mode is by using the prefers-color-scheme
media query. This allows you to automatically detect the user's theme preference from their operating system.
/* Light theme (default) */
body {
background-color: white;
color: black;
}
/* Dark theme */
@media (prefers-color-scheme: dark) {
body {
background-color: black;
color: white;
}
}
This method works automatically based on the browser and user’s system settings. However, if the user wants to switch manually, you'll need JavaScript support.
2. Manual Theme Switching with JavaScript
Some users prefer to switch themes manually. For that, you can create a toggle button to switch between light and dark mode.
HTML
<button id='themeToggle'>Dark Mode</button>
CSS
body.dark {
background-color: black;
color: white;
}
JavaScript
document.addEventListener('DOMContentLoaded', function() {
let button = document.getElementById('themeToggle');
button.addEventListener('click', function() {
document.body.classList.toggle('dark');
button.textContent = document.body.classList.contains('dark') ? '☀️ Light Mode' : '🌙 Dark Mode';
});
});
- Toggles the
dark
class on thebody
element. - Updates the button label dynamically.
- Provides a simple and lightweight switch.
3. Saving User Preference with LocalStorage
To preserve the user's preferred theme across page reloads or future visits, use LocalStorage.
Updated JavaScript
document.addEventListener('DOMContentLoaded', function() {
let button = document.getElementById('themeToggle');
let savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.body.classList.add('dark');
button.textContent = '☀️ Light Mode';
}
button.addEventListener('click', function() {
document.body.classList.toggle('dark');
let newTheme = document.body.classList.contains('dark') ? 'dark' : 'light';
localStorage.setItem('theme', newTheme);
button.textContent = newTheme === 'dark' ? '☀️ Light Mode' : '🌙 Dark Mode';
});
});
This enhancement saves the user's preference and restores it on page reload—improving the user experience.
Adding dark mode support to your website is an important improvement both in terms of aesthetics and usability. You can use the prefers-color-scheme
media query for automatic switching, enable manual control with JavaScript, and store preferences with LocalStorage.
Now go ahead and add dark mode to your own site to improve user experience! 🌙✨
Related Articles
