Hi
How to make a theme switcher with HTML, CSS and JavaScript
This is a simple way to setup theming support for your web project - no framework or library required. You can use an almost identical process to add light / dark mode.
The HTML
<body>
<div class="bg" style="width: 300px; padding: 20px">
<select>
<option>Snow theme</option>
<option>Jungle theme</option>
</select>
<span class="text">This text will change color!</span>
</div>
</body>
The bg
class will apply our current theme's background color, and the text
class will
apply our current theme's text color.
The CSS
We will use CSS variables to achieve our goal.
:root {
/* Creating a CSS variable */
--background-color: #2e3440;
--foreground-color: #eceff4;
}
.jungle-theme {
/* Redefining the variables for the jungle-theme class */
--background-color: #a3be8c;
--foreground-color: #182f18;
}
.bg {
/* This is how we use the variables */
background: var(--background-color);
}
.text {
color: var(--foreground-color);
}
The JavaScript
const bodyElement = document.querySelector("body");
const selectElement = document.querySelector("select");
selectElement.addEventListener("change", () => {
if (selectElement.selectedIndex === 0) {
bodyElement.classList.remove("jungle-theme");
} else if (selectElement.selectedIndex === 1) {
bodyElement.classList.add("jungle-theme");
}
});
If you intend to add more themes then you would refactor this, but this should give you the general idea.
How it works
At the heart of the solution is CSS variables. By redefining the variables under another class jungle-theme, we can apply that class to any element - which will override the default values of the variables which we set in :root. By adding the class to body, all of body's children will get the variables as well. Removing the class reverts the variables to their previous values.
With the JavaScript, we simply toggle the CSS class on the body element. This can be done on the click of a button, or in our case, when a select value changes.
This was a very basic example of the technique. In a full web project, you would have more variables and reuse them in many CSS classes.
You can use the same technique to implement light / dark mode. To add automatic dark mode,
simply use the prefers-color-scheme: dark
media feature
to redefine the CSS variables.