Demo
The code below is what I use on this website – scroll/swipe down to the footer and play with the options within Color scheme to see it in action.
Code
What follows will allow a visitor to choose between light mode, dark mode, or the mode their device is currently in (which I’ve labeled System). This System option is useful if the visitor’s device is configured to automatically switch between light and dark modes based on the time of day.
HTML
Fairly straightfoward HTML; mark it up however you see fit, just make sure the <input> elements keep these attributes.
<label>
<input type="radio" name="color-scheme" value="light dark">
System
</label>
<label>
<input type="radio" name="color-scheme" value="light">
Light
</label>
<label>
<input type="radio" name="color-scheme" value="dark">
Dark
</label>
JavaScript
A dash of JavaScript to implement the visitor’s Color scheme choice, save it to the localStorage on their device, and retrieve it when they come back.
const selectedColorScheme = localStorage.getItem('color-scheme') || 'light dark';
const applyScheme = (scheme) => {
localStorage.setItem('color-scheme', scheme);
document.documentElement.style.setProperty('color-scheme', scheme);
document.querySelector(`[name="color-scheme"][value="${scheme}"]`).checked = true;
}
applyScheme(selectedColorScheme);
document.querySelectorAll('[name="color-scheme"]').forEach(radio => {
radio.addEventListener('change', (e) => {
applyScheme(e.target.value);
});
});
CSS
When defining colors in the CSS, utilize the light-dark() color function to define two colors – light first, then dark. The visitor’s web browser will use one of these two colors based on the color scheme choice they’ve made.
/* For example… */
body {
background-color: light-dark(#ddd, #333);
color: light-dark(#111, #eee);
}
.other-elements {
border-color: light-dark(#ffcc99, #cc0099);
}