How can I use CSS variables to change the theme of my website dynamically?
Asked on Oct 11, 2025
Answer
CSS variables, also known as custom properties, allow you to define reusable values that can be dynamically changed to update your website's theme. Here's how you can implement them:
<!-- BEGIN COPY / PASTE -->
<style>
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--background-color: #ecf0f1;
}
body {
background-color: var(--background-color);
color: var(--primary-color);
}
.button {
background-color: var(--secondary-color);
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
<button class="button" onclick="changeTheme()">Change Theme</button>
<script>
function changeTheme() {
document.documentElement.style.setProperty('--primary-color', '#e74c3c');
document.documentElement.style.setProperty('--secondary-color', '#8e44ad');
document.documentElement.style.setProperty('--background-color', '#34495e');
}
</script>
<!-- END COPY / PASTE -->Additional Comment:
- CSS variables are defined within a selector using the "--" prefix, typically in the ":root" for global scope.
- To apply a CSS variable, use the "var()" function, such as "var(--primary-color)".
- JavaScript can dynamically change CSS variables using "document.documentElement.style.setProperty()".
- This approach allows for easy theme switching by updating variable values, which automatically updates all elements using those variables.
Recommended Links: