Last active
September 1, 2023 13:02
-
-
Save max-m/2bbeb6848b24895b841ebbd20f9d0159 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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