Ask any question about CSS here... and get an instant response.
Post this Question & Answer:
How can I use CSS variables to create a dark mode toggle?
Asked on Apr 01, 2026
Answer
CSS variables, also known as custom properties, allow you to define reusable values in your stylesheets, which makes implementing a dark mode toggle efficient and straightforward. Here's a basic example of how to achieve this.
<!-- BEGIN COPY / PASTE -->
<style>
:root {
--bg-color: white;
--text-color: black;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
.dark-mode {
--bg-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 using "var(--variable-name)".
- The ":root" selector targets the document's root element, making the variables globally accessible.
- The "transition" property is used to animate the change in background and text colors smoothly.
- The "toggleDarkMode" function adds or removes the "dark-mode" class, altering the CSS variables' values.
Recommended Links:
