/ Gists / CSS variables (get/set + javascript)
On gists

CSS variables (get/set + javascript)

Popular ⭐ JavaScript CSS CSS trick

usage.js Raw #

// Getting a CSS Variable's Value
getComputedStyle(document.documentElement) // or specific element
    .getPropertyValue('--my-variable-name'); // #999999
    
  
// Setting a CSS Variable's Value
document.documentElement.style // or specific element
    .setProperty('--my-variable-name', 'pink');
    
    
// OR
var root = document.querySelector(':root'); // = document.documentElement

index.js Raw #

/* css */
/* can be any HTML element not only ROOT */
:root {
  --phone: 50px;
  --tablet: 800px;
  

}

#test {
  background: red;
  height: 50px;
  width: var(--phone);
}

/* js */
const breakpointsData = document.querySelector(':root');

const phone = getComputedStyle(breakpointsData)
    .getPropertyValue('--phone');


setTimeout(() => {
  breakpointsData.style
    .setProperty('--phone', '100px');
}, 1000)