Skip to content

Instantly share code, notes, and snippets.

@max-m
Last active September 1, 2023 13:02
Show Gist options
  • Save max-m/2bbeb6848b24895b841ebbd20f9d0159 to your computer and use it in GitHub Desktop.
Save max-m/2bbeb6848b24895b841ebbd20f9d0159 to your computer and use it in GitHub Desktop.
const setStyleVar = (name, value) => {
document.documentElement.style.setProperty(`--${name}`, value);
}
const getStyleVar = name => {
return getComputedStyle(document.documentElement).getPropertyValue(`--${name}`);
}
/// `z-index` is an <Integer> property, we can abuse that to get the evaluated value of a CSS variable
const getStyleVarInt = name => {
// We create a hidden DOM element, add it to the document and query the CSS engine for the property we're interested in
const dummy = document.createElement('div');
dummy.style.display = 'none';
dummy.style.setProperty('z-index', `var(--${name})`);
document.body.appendChild(dummy);
const value = Number.parseInt(getComputedStyle(dummy).getPropertyValue('z-index'));
dummy.remove();
return value;
}
/// `width` is avaluated in <Pixels>, we can abuse that as well
const getStyleVarPixels = name => {
const dummy = document.createElement('div');
dummy.style.display = 'none';
dummy.style.setProperty('width', `var(--${name})`);
document.body.appendChild(dummy);
const value = Number.parseFloat(getComputedStyle(dummy).getPropertyValue('width').replace(/px$/, ''));
dummy.remove();
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment