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 theme?
Asked on Jan 23, 2026
Answer
CSS variables, also known as custom properties, allow you to define reusable values in your stylesheets, making it easy to switch themes like dark mode. Here's a basic example of how to implement a dark mode using CSS variables.
<!-- BEGIN COPY / PASTE -->
<style>
:root {
--background-color: white;
--text-color: black;
}
.dark-mode {
--background-color: black;
--text-color: white;
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
</style>
<body>
<button onclick="toggleDarkMode()">Toggle Dark Mode</button>
<script>
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
}
</script>
</body>
<!-- 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 targets the document's root element, making the variables globally accessible.
- JavaScript can be used to toggle a class that switches between light and dark mode by changing the CSS variable values.
- This approach allows for easy theme management and can be extended to include more variables for other style properties.
Recommended Links:
