Today I learned how to use CSS variables (custom properties) to implement theme switching between light and dark modes.
Defining CSS Variables
First, define your variables in the :root selector:
:root {
/* Light theme (default) */
--background-color: #ffffff;
--text-color: #333333;
--primary-color: #4285f4;
}
/* Dark theme */
.dark {
--background-color: #1a1a1a;
--text-color: #f0f0f0;
--primary-color: #8ab4f8;
}
Using the Variables
Then use these variables throughout your CSS:
body {
background-color: var(--background-color);
color: var(--text-color);
}
.button {
background-color: var(--primary-color);
color: white;
}
JavaScript for Theme Switching
Add JavaScript to toggle the theme:
// Check for saved theme preference or use the system preference
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const savedTheme = localStorage.getItem("theme");
// Apply the saved theme or use system preference
if (savedTheme === "dark" || (!savedTheme && prefersDarkScheme.matches)) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
// Toggle theme when button is clicked
document.getElementById("theme-toggle").addEventListener("click", () => {
if (document.documentElement.classList.contains("dark")) {
document.documentElement.classList.remove("dark");
localStorage.setItem("theme", "light");
} else {
document.documentElement.classList.add("dark");
localStorage.setItem("theme", "dark");
}
});
This approach is much cleaner than having separate stylesheets or using JavaScript to change styles directly!