🌗 Dark / Light Theme Toggle with HTML, CSS & JavaScript
In this project, we'll build a beautiful theme toggle button to switch between dark and light modes. This is one of the most common features in modern websites.
Google Advertisement
📁 HTML Structure
<div class="container">
<h2>Toggle Theme Demo</h2>
<button id="toggleBtn">Switch to Dark Mode</button>
<p>This is a simple paragraph to demonstrate the theme.</p>
</div>
🎨 CSS Styling
:root {
--bg-color: #ffffff;
--text-color: #000000;
--btn-bg: #dddddd;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
font-family: Arial, sans-serif;
transition: all 0.3s;
padding: 40px;
}
.container {
max-width: 600px;
margin: auto;
text-align: center;
}
button {
background: var(--btn-bg);
padding: 10px 20px;
border: none;
cursor: pointer;
font-size: 16px;
}
⚙️ JavaScript Logic
const toggleBtn = document.getElementById('toggleBtn');
let darkMode = false;
toggleBtn.addEventListener('click', function () {
darkMode = !darkMode;
if (darkMode) {
document.documentElement.style.setProperty('--bg-color', '#121212');
document.documentElement.style.setProperty('--text-color', '#ffffff');
document.documentElement.style.setProperty('--btn-bg', '#333333');
toggleBtn.textContent = 'Switch to Light Mode';
} else {
document.documentElement.style.setProperty('--bg-color', '#ffffff');
document.documentElement.style.setProperty('--text-color', '#000000');
document.documentElement.style.setProperty('--btn-bg', '#dddddd');
toggleBtn.textContent = 'Switch to Dark Mode';
}
});
Google Advertisement
🚀 Live StackBlitz Demo
💡 Improvements You Can Add
Google Advertisement
- Save theme preference in
localStorage
- Detect system preference with
prefers-color-scheme
- Use toggle switches instead of buttons
- Add animations between themes
📚 Conclusion
This Dark/Light Theme Toggle is a useful mini project for practicing CSS variables, DOM manipulation, and adding personalized user experience to web apps. It's also a feature expected in modern UI design.