Ask any question about CSS here... and get an instant response.
How can I use CSS variables to create a dark mode theme switcher for my website?
Asked on Nov 03, 2025
Answer
CSS variables, also known as custom properties, allow you to define reusable values that can be dynamically changed to implement features like a dark mode theme. Here's a basic example of how to set up a theme switcher using CSS variables.
<!-- BEGIN COPY / PASTE -->
<style>
:root {
--background-color: white;
--text-color: black;
}
body {
background-color: var(--background-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
.dark-mode {
--background-color: black;
--text-color: white;
}
</style>
<button onclick="toggleDarkMode()">Toggle Dark Mode</button>
<script>
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
}
</script>
<!-- END COPY / PASTE -->Additional Comment:
- CSS variables are defined using the syntax "--variable-name: value;" and can be accessed with "var(--variable-name)".
- The ":root" selector is used to define global CSS variables that can be accessed throughout the document.
- JavaScript is used here to toggle a class on the body element, which changes the CSS variable values to switch themes.
- Transitions are applied to smoothly animate the color changes when switching themes.
Recommended Links:
