EN
CSS - set CSS variable using JavaScript
3
points
In this article, we would like to show you how to set CSS variable using JavaScript.
Quick solution:
var root = document.querySelector(':root'); // gets root element
function setVariable(name, value) {
root.style.setProperty(name, value);
}
// Usage example:
setVariable('--variable-name', 'variable-value');
Practical example
In this example, we set --primary-color variable with orange value, then we use it as a background for a div element with .primary class.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
div.primary {
background: var(--primary-color);
}
</style>
</head>
<body>
<script>
var root = document.querySelector(':root'); // gets root element
function setVariable(name, value) {
root.style.setProperty(name, value);
}
// Usage example:
setVariable('--primary-color', 'orange'); // sets --primary-color with orange value
</script>
<div class="primary">This div background color uses --primary-color variable that has been set using JavaScript</div>
</body>
</html>