Skip to content

Instantly share code, notes, and snippets.

@oelna
Created May 31, 2024 14:13
Show Gist options
  • Save oelna/0bfbbbf30d2de92b6bb33766cd7bd1bf to your computer and use it in GitHub Desktop.
Save oelna/0bfbbbf30d2de92b6bb33766cd7bd1bf to your computer and use it in GitHub Desktop.
CSS light/dark mode with manual toggle
<!doctype html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8">
<title>dark mode</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<label class="theme-switch" for="cb">
<input type="checkbox" id="cb" /> Toggle Mode
</label>
</body>
</html>
/* manual toggle */
const toggleSwitch = document.querySelector('.theme-switch input');
toggleSwitch.addEventListener('change', function (e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark');
} else {
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('theme', 'light');
}
}, false);
/* read localstorage on load */
const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
if (currentTheme) { // localstorage setting exists
document.documentElement.setAttribute('data-theme', currentTheme);
if (currentTheme === 'dark') {
toggleSwitch.checked = true;
}
} else { // localstorage setting missing, read OS setting
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.setAttribute('data-theme', 'dark');
toggleSwitch.checked = true;
}
}
// react to OS setting change, if no localstorage setting exists
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function (event) {
if (currentTheme) return;
const newColorScheme = event.matches ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', newColorScheme);
if (newColorScheme === 'dark') {
toggleSwitch.checked = true;
} else {
toggleSwitch.checked = false;
}
});
/*
@media (prefers-color-scheme: light) {
:root {
}
}
@media (prefers-color-scheme: dark) {
:root {
--test: #333;
}
}
*/
:root {
color-scheme: light dark;
--test: #fff;
}
[data-theme="dark"] {
--test: #333;
}
html {
background: var(--test);
}
@oelna
Copy link
Author

oelna commented May 31, 2024

@oelna
Copy link
Author

oelna commented May 31, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment