Theme Toggle Switch
Home
Snippets
Theme Toggle Switch
HTML
CSS
JS
<div class="toggle-container"> <div class="toggle-btn" id="theme-toggle"></div> </div> <h1> Toggle Dark/Light Mode </h1> <p style="text-align:center;">Click the switch in the top-right corner to change theme.</p>
body { margin: 0; font-family: Arial, sans-serif; transition: background 0.4s, color 0.4s; background: #ffffff; color: #222; } .dark-mode { background: #121212; color: #f5f5f5; } .toggle-container { position: fixed; top: 20px; right: 20px; } .toggle-btn { width: 60px; height: 30px; background: #ddd; border-radius: 30px; position: relative; cursor: pointer; transition: background 0.3s; } .toggle-btn::before { content: ""; width: 24px; height: 24px; background: #fff; border-radius: 50%; position: absolute; top: 3px; left: 3px; transition: transform 0.3s; } .dark-mode .toggle-btn { background: #555; } .dark-mode .toggle-btn::before { transform: translateX(30px); background: #ffdd57; } h1 { text-align: center; margin-top: 100px; }
const toggle = document.getElementById('theme-toggle'); const body = document.body; if (localStorage.getItem("theme") === "dark") { body.classList.add("dark-mode"); } toggle.addEventListener("click", () => { body.classList.toggle("dark-mode"); if (body.classList.contains("dark-mode")) { localStorage.setItem("theme", "dark"); } else { localStorage.setItem("theme", "light"); } });
Ad #1
Ad #2
Scroll to Top