The problem
You need to implement dark and light mode with easy theme switching.
The solution
:root {
/* Light mode (default) */
--bg-primary: #ffffff;
--bg-secondary: #f5f5f5;
--text-primary: #1a1a1a;
--text-secondary: #666666;
--accent: #3a7bff;
--border: #e0e0e0;
--shadow: rgba(0, 0, 0, 0.1);
}
[data-theme="dark"] {
--bg-primary: #0d1126;
--bg-secondary: #1a1a2e;
--text-primary: #ffffff;
--text-secondary: #a0a0a0;
--accent: #3a7bff;
--border: #2a2a4e;
--shadow: rgba(0, 0, 0, 0.3);
}
/* Auto dark mode based on system preference */
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg-primary: #0d1126;
--bg-secondary: #1a1a2e;
--text-primary: #ffffff;
--text-secondary: #a0a0a0;
--border: #2a2a4e;
--shadow: rgba(0, 0, 0, 0.3);
}
}
/* Usage */
body {
background: var(--bg-primary);
color: var(--text-primary);
}
.card {
background: var(--bg-secondary);
border: 1px solid var(--border);
box-shadow: 0 4px 12px var(--shadow);
}See it live
Put it to work
<!-- Toggle theme with JavaScript -->
<button onclick="toggleTheme()">Toggle Theme</button>
<script>
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
}
</script>Worth knowing
Store theme preference in localStorage. Use prefers-color-scheme for automatic detection.