🌙 Dark Mode Toggle

3 implementations: toggle switch, system preference detection, and localStorage persistence.

🎮 Live Demo
Try the toggle below – your preference is saved automatically.

🌓 Toggle Switch

☀️ 🌙

Click the toggle to switch themes. Your preference is saved automatically.

💻 System Preference

This page detects your OS/browser dark mode setting.

🔄 Manual Reset

Clear saved preference and use system default.

💻 Complete Code
<!-- CSS Variables -->
:root {
  --bg-primary: #f8fafc;
  --text-primary: #0f172a;
  --border: #e2e8f0;
}

[data-theme="dark"] {
  --bg-primary: #0f172a;
  --text-primary: #f1f5f9;
  --border: #334155;
}

body {
  background: var(--bg-primary);
  color: var(--text-primary);
  transition: background 0.3s, color 0.3s;
}

<!-- HTML Toggle Switch -->
<label class="theme-switch">
  <input type="checkbox" id="darkModeToggle">
  <span class="slider"></span>
</label>

<!-- JavaScript (Core) -->
function setTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme);
  localStorage.setItem('theme', theme);
  const toggle = document.getElementById('darkModeToggle');
  if (toggle) toggle.checked = (theme === 'dark');
}

function getSystemTheme() {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

// Initialize
const savedTheme = localStorage.getItem('theme');
setTheme(savedTheme || getSystemTheme());

// Listen to toggle
document.getElementById('darkModeToggle').addEventListener('change', (e) => {
  setTheme(e.target.checked ? 'dark' : 'light');
});
📖 How It Works

🚀 Need More Dark Mode Variations?

Get advanced dark mode implementations in the Pro Pack: multiple theme colors, gradient themes, and theme picker with color wheel.

Get Pro Pack – $7 →

❤️ Found This Useful?

This free snippet took time to build. A small coffee keeps them coming.

☕ Buy Me a Coffee
← Back to all snippets