CSS Using JavaScript to Change Variables
- Previous Page CSS Overlapping Variables
- Next Page CSS Variables - Media Queries
Change variables using JavaScript
CSS variables can access the DOM, which means you can change them with JavaScript.
This example demonstrates how to create a script to display and change the --blue variable used in the example on the previous page. If you are not familiar with JavaScript, don't worry. You can learn more about JavaScript in our JavaScript tutorial:
Example
<script> // Get the root element var r = document.querySelector(':root'); // Create a function to get the value of the variable function myFunction_get() { // Get the styles (properties and values) for the root var rs = getComputedStyle(r); // Alert the value of the --blue variable alert("The value of --blue is: " + rs.getPropertyValue('--blue')); } // Create a function to set the value of the variable function myFunction_set() { // Set the value of variable --blue to another value (in this case "lightblue") r.style.setProperty('--blue', 'lightblue'); } </script>
Browser Support
The numbers in the table indicate the first browser version that fully supports this property.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
CSS var() Function
Function | Description |
---|---|
var() | Insert the value of the CSS variable. |
- Previous Page CSS Overlapping Variables
- Next Page CSS Variables - Media Queries