Extracting the value of a css variable to display
2023-01-11I needed to extract the value of a global CSS variable to print on a documentation site. I wanted this so that the docs didn’t have to be updated whenever the css styles are updated.
In the global CSS, I had the following variable
:root {
--color-black: hsl(0,0%,5%);
}
On the Window you can getComputedStyle of an element. Since I’m doing this on a client side Svelte component, I used this simple function to return the value.
function printCssValue(cssValue: string) {
const styles = getComputedStyle(document.documentElement);
const value = styles.getPropertyValue(cssValue);
return value ? value.trim().toUpperCase() : '';
}
Things to note
getPropertyValue will return a string with a leading space so that is why I had to trim() the string.