đ What is Dark Mode in Web Development?
Dark Mode is a design feature that displays your website or app with light text on a dark background, reducing eye strain in low-light environments and improving battery life on OLED screens.
â Itâs now expected by users, supported natively in CSS, and considered a best practice in modern UI/UX.
đš Benefits of Dark Mode
Benefit | Why It Matters |
---|---|
đ Reduces Eye Strain | Especially in dark environments |
đ Saves Battery | On OLED and AMOLED screens |
đ§ Aesthetic | Trendy, sleek, modern design feel |
đĄ Accessibility | Helps users sensitive to bright light |
đ Customization | Gives users control over their experience |
âïž 3 Ways to Implement Dark Mode
â 1. CSS Media Query (Auto-Detect System Preference)
/* Default (light mode) */
body {
background: #fff;
color: #000;
}
/* Dark mode (based on OS setting) */
@media (prefers-color-scheme: dark) {
body {
background: #121212;
color: #ffffff;
}
}
đ Automatically switches based on userâs system preference.
â 2. Manual Toggle (Light/Dark Button)
HTML:
<button id="toggle-theme">Toggle Theme</button>
JavaScript:
const btn = document.getElementById('toggle-theme');
btn.addEventListener('click', () => {
document.body.classList.toggle('dark');
});
CSS:
body.dark {
background: #1e1e1e;
color: #f1f1f1;
}
đ§ Add
localStorage
to remember the theme between sessions:
// Save theme
localStorage.setItem('theme', 'dark');
// Apply saved theme
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark');
}
â 3. With Tailwind CSS
If youâre using Tailwind CSS, it’s even easier:
tailwind.config.js:
module.exports = {
darkMode: 'class', // or 'media'
// ...
};
Example HTML:
<body class="dark:bg-gray-900 dark:text-white">
<h1 class="text-black dark:text-white">Hello</h1>
</body>
đŠ Bonus: Dark Mode in JavaScript Frameworks
Framework | Dark Mode Strategy |
---|---|
React | Context API, Tailwind, or CSS vars |
Vue | class toggling with Vuex or localStorage |
Svelte | writable store with class:dark |
Next.js | next-themes package is popular |
Nuxt.js | Built-in theme toggling support |
â Best Practices
Respect system preference using
prefers-color-scheme
Give users manual toggle (and remember preference)
Ensure good contrast for accessibility (check with WCAG)
Test across devices and screens (mobile dark mode behaves differently)
Use semantic colors â like
--color-bg
â instead of hardcoding colors