Dark Mode Toggle with Local Storage
What this snippet does
Give any site a modern dark mode in one shot. This tiny snippet:
- Uses CSS variables for colors (no redesign needed)
- Respects the visitor’s system preference (light or dark)
- Remembers their choice with
localStorage - Adds a small ☾/☀ toggle button in the bottom-right corner
No frameworks, no build tools, no tracking — just a clean, vibe-coded switch your visitors will actually use. 🌙
Copy-paste snippet
Drop this near the end of your <body> (or in your main template) on any page you want to support dark mode:
<style>
:root {
--bg-color: #ffffff;
--text-color: #111111;
}
[data-theme="dark"] {
--bg-color: #050816;
--text-color: #f9fafb;
}
body {
background: var(--bg-color);
color: var(--text-color);
transition: background 0.2s ease, color 0.2s ease;
}
/* Floating toggle button */
.dark-toggle {
position: fixed;
right: 16px;
bottom: 16px;
padding: 6px 12px;
font-size: 13px;
border-radius: 999px;
border: 1px solid rgba(0, 0, 0, 0.2);
background: rgba(255, 255, 255, 0.9);
cursor: pointer;
z-index: 9999;
}
[data-theme="dark"] .dark-toggle {
background: rgba(15, 23, 42, 0.9);
color: #f9fafb;
border-color: rgba(148, 163, 184, 0.9);
}
</style>
<button type="button" class="dark-toggle" aria-label="Toggle dark mode">☾ Dark</button>
<script>
(function () {
var storageKey = 'vibe-theme';
var root = document.documentElement;
var btn;
function applyTheme(theme) {
root.setAttribute('data-theme', theme);
try {
localStorage.setItem(storageKey, theme);
} catch (e) {
// localStorage disabled; ignore
}
if (btn) {
btn.textContent = theme === 'dark' ? '☀ Light' : '☾ Dark';
}
}
function getPreferredTheme() {
var stored = null;
try {
stored = localStorage.getItem(storageKey);
} catch (e) {
stored = null;
}
if (stored === 'light' || stored === 'dark') {
return stored;
}
if (window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
return 'light';
}
document.addEventListener('DOMContentLoaded', function () {
btn = document.querySelector('.dark-toggle');
if (!btn) return;
applyTheme(getPreferredTheme());
btn.addEventListener('click', function () {
var current = root.getAttribute('data-theme');
var next = current === 'dark' ? 'light' : 'dark';
applyTheme(next);
});
});
})();
</script>
How to use it
- Paste the snippet above right before
</body>on your page or layout. - Optionally tweak the
--bg-colorand--text-colorvalues for your own light/dark palette. - Reload your site and click the toggle in the bottom-right to switch between ☾ Dark and ☀ Light. The choice will stick on refresh.
That’s it — a lightweight dark mode toggle that feels like a native feature, not another bulky widget.