Ask any question about CSS here... and get an instant response.
Post this Question & Answer:
How can I use CSS variables to create a theme switcher for dark and light modes?
Asked on May 22, 2026
Answer
CSS variables, also known as custom properties, are a powerful way to implement theme switching, such as toggling between dark and light modes. They allow you to define reusable values that can be changed dynamically.
<!-- BEGIN COPY / PASTE -->
<style>
:root {
--background-color: white;
--text-color: black;
}
.dark-theme {
--background-color: black;
--text-color: white;
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
</style>
<button onclick="document.body.classList.toggle('dark-theme')">
Toggle Theme
</button>
<!-- END COPY / PASTE -->Additional Comment:
- CSS variables are defined using the "--" prefix and are scoped to the element they are declared on, often ":root" for global scope.
- Use "var(--variable-name)" to apply the variable in your CSS rules.
- The example uses JavaScript to toggle the "dark-theme" class on the body element, which switches the theme.
- This method allows for easy theme management and dynamic updates without changing multiple CSS rules manually.
Recommended Links:
