3 implementations: toggle switch, system preference detection, and localStorage persistence.
Click the toggle to switch themes. Your preference is saved automatically.
This page detects your OS/browser dark mode setting.
Clear saved preference and use system default.
<!-- 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');
});
:root and override with [data-theme="dark"]window.matchMedia('(prefers-color-scheme: dark)')Get advanced dark mode implementations in the Pro Pack: multiple theme colors, gradient themes, and theme picker with color wheel.
Get Pro Pack – $7 →This free snippet took time to build. A small coffee keeps them coming.
☕ Buy Me a Coffee