CSS Variables (Variables with JavaScript)

Change Variables With JavaScript

CSS variables have access to the DOM, which means that you can change them with JavaScript.

Here is an example of how you can create a script to display and change the --blue variable in the example given below.

Example HTML

:root {
--blue: #1e90ff;
--white: #ffffff;
}

body {
background-color: var(--blue);
}

h2 {
border-bottom: 2px solid var(--blue);
}

.container {
color: var(--blue);
background-color: var(--white);
padding: 15px;
}

button {
background-color: var(--white);
color: var(--blue);
border: 1px solid var(--blue);
padding: 5px;
}

Example Script

<script>
// Get the root element
var r = document.querySelector(':root');

// Create a function for getting a variable value
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 for setting a variable value
function myFunction_set() {
// Set the value of variable --blue to another value (in this case "lightblue")
r.style.setProperty('--blue', 'lightblue');
}
</script>


  • getComputedStyle(r) - This function gets all the properties and it's values declared in the :root selector.
  • getPropertyValue('--blue') - This function gets the value of --blue variable declared in the :root selector.
  • setProperty('--blue', 'lightblue') - This function sets the value of --blue variable to lightblue.

CSS var() Function

Property Description
var() Inserts the value of a CSS variable

Comments