To change a CSS variable (--height
) in JavaScript, you can use:
var r = document.querySelector(':root');
r.style.setProperty('--height', <YOUR_HEIGHT>+'px');
Here is a small example where we change a CSS variable (--width
) on a button click:
var r = document.querySelector(':root');
r.style.setProperty('--width', '100px');
function swapSize() {
if (getComputedStyle(r).getPropertyValue('--width') == '100px') {
r.style.setProperty('--width', '200px');
} else {
r.style.setProperty('--width', '100px');
}
}
:root {
--width: 100px
}
div {
height: 100px;
width: var(--width);
background-color: blue;
}
<div></div>
<button onclick="swapSize()">swap variable value</button>