Hello, fellow developer! Today, let’s brighten—or dim—your day by learning how to implement a light/dark theme toggle in your app.
Why Add a Theme Toggle?
Dark mode improves readability in low light, conserves battery, and gives users visual control. It also enhances UX by respecting user preferences.
Setting the Stage
We’ll follow three steps:
- Define CSS Variables for both light and dark themes
- Create a Toggle Button
- Use JavaScript to switch and persist themes
Step 1: Defining CSS Variables
:root {
--background-color: #ffffff;
--text-color: #000000;
}
[data-theme='dark'] {
--background-color: #000000;
--text-color: #ffffff;
}
body {
background-color: var(--background-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s; /* Smooth transition */
}
Step 2: Creating the Toggle Button
<button id="theme-toggle">Toggle Theme</button>
Basic CSS to position and style the button:
#theme-toggle {
position: absolute;
top: 10px;
right: 10px;
padding: 10px;
cursor: pointer;
}
Step 3: Handling Theme with JavaScript
const toggleButton = document.getElementById('theme-toggle');
// Check local storage for the user's theme preference
const currentTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', currentTheme);
// Toggle theme when button is clicked
toggleButton.addEventListener('click', function () {
const newTheme = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme); // Save user's preference
});
Explanation:
data-themeis toggled betweenlightanddark.- The setting is stored in
localStorageso the preference persists on reload.
Bonus: A Fancier Toggle Switch
<label class="theme-switch">
<input type="checkbox" id="theme-checkbox">
<span class="slider"></span>
</label>
.theme-switch {
position: fixed;
display: inline-block;
width: 60px;
height: 34px;
}
.theme-switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0; left: 0; right: 0; bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
Conclusion
Congrats! 🎉 You’ve added a sleek theme toggle to your site or app. By combining CSS variables with JavaScript logic and local storage, you’ve created an adaptive UI your users will appreciate.
Optional Practice:
- 🔍 Add ARIA labels for accessibility
- 💾 Persist the theme across multiple pages
- 💫 Add smooth transitions for a more professional look
Happy coding—and keep your UI bright or dark, just how your users like it! 😊
(Visited 10 times, 1 visits today)
