Academy / Advanced Level: HTML and CSS
CSS Variables (Custom Properties)
Dynamic CSS Variables with JavaScript
CSS Variables can be manipulated dynamically using JavaScript, enabling powerful interactions and theme-switching functionality.
Example: Changing Variables with JavaScript
You can access and update CSS Variables using the setProperty() method on the document’s style property.
<button onclick="changePrimaryColor('#e74c3c')">Change Color</button>
<script>
function changePrimaryColor(newColor) {
document.documentElement.style.setProperty('--primary-color', newColor);
}
</script>
In this example, clicking the button will change the --primary-color to a new value, dynamically updating the styles on the page.