Quick tricks - offer your app in dark or light mode in pure CSS
Using the light dark CSS color-scheme you can offer your app in light or dark mode in pure CSS. No need for any frameworks, media queries or JavaScript.
html {
--darker: oklch(0% 0 0);
--lighter: oklch(100% 0 0);
color-scheme: light dark;
}
body {
font-family: sans-serif;
background-color: light-dark(var(--lighter), var(--darker));
color: light-dark(var(--darker), var(--lighter));
}
You can even set parts of the page as one mode or another and by manipulating the color-scheme CSS style setting you can create a theme switcher in a few lines of JavaScript, keeping all the functionality in the CSS engine. Check out this codepen to see it action.
let doc = document.querySelector('html');
let themetoggle = false;
let button = document.querySelector('button');
button.addEventListener('click', e => {
themetoggle ? doc.style.colorScheme ='dark' :
doc.style.colorScheme = 'light';
themetoggle = !themetoggle;
})
Users have a preference, though, there is no need to offer a dark/light switcher, and with this new CSS functionality you don’t even need to think about it.
These tricks are part of the Dev Digest Newsletter.