How to add a theme switcher with CSS variables
If you want to give the user more control over the theme, you can add a theme switcher that lets them toggle between the light and dark mode manually. To do this, you need to add some HTML elements that act as buttons or checkboxes for the theme switcher. For example, you can use a label and an input of type checkbox like this:
<label for="theme-switcher">Dark mode</label>
<input type="checkbox" id="theme-switcher">
Then, you need to use some JavaScript code to listen for the change event on the input element and add or remove a class name from the html element based on the checked state of the input. For example, you can use a class name of dark-theme to indicate that the user has selected the dark mode like this:
const themeSwitcher = document.getElementById("theme-switcher");
themeSwitcher.addEventListener("change", function() {
if (this.checked) {
document.documentElement.classList.add("dark-theme");
} else {
document.documentElement.classList.remove("dark-theme");
}
});
Next, you need to use a CSS selector that targets the html element with the dark-theme class name and override the variables with the values for the dark theme. For example, you can use the same values as before for the background color and the text color, like this:
html.dark-theme {
--body-bg-color: #000000;
--text-color: #ffffff;
}
Finally, you need to use the variables in your CSS rules to apply the style properties to the elements that you want to change for the dark theme. For example, you can use the same rule as before for the body element and add another rule for the text color like this:
body {
background-color: var(--body-bg-color);
}
p {
color: var(--text-color);
}
This way, the style properties will change based on the class name of the html element, which is controlled by the theme switcher.