Hey everyone, I wanted to share a simple way to access CSS variables through Javascript.
Sometimes this is necessary so if you ever need it here’s how to do it.
<style>
// Define your variables at the root level in CSS
// This can also be in a separate CSS file, and that works just fine
:root {
--color_primary: #ff0000;
}
</style>
<script>
// This function gets a CSS variable from the root document element
function getCSSVar(variable) {
return window.getComputedStyle(document.documentElement).getPropertyValue('--' + variable);
}
// Example usage
document.write('The primary color is: ' + getCSSVar('color_primary'));
</script>
Toby said: @Aris
I wonder how much of that could be handled with container query units and something like round() these days. Modern CSS is insanely powerful.
Sal said: @Aris
Shouldn’t you just use… grid instead?
Probably yes! I just didn’t know about grid at that point.
I remember the solution was for creating dynamically sized cards on a storefront, and when the sidebar opened, instead of making the cards smaller, I just reduced the column count instead.
Sal said: @Aris
Seems like grid would be much better for that since you can set columns dynamically based on how many can fit.
I agree!
I just didn’t know grid existed back then in my studies. It may not have been a great overall example of a website (though functional) but I wanted to share something relevant to the original post.
Using CSS variables in math operations and adjusting them with JavaScript feels powerful to me, and I think it has potential.
Everyone talks about code smells but no one ever describes what they smell like Fish? Wet dog? Or something rich and vibrant like peach syrup or the smell of dirt after it rains.
Fraser said:
Everyone talks about code smells but no one ever describes what they smell like Fish? Wet dog? Or something rich and vibrant like peach syrup or the smell of dirt after it rains.
There’s a list of smells in Martin Fowler’s Refactoring book. Definitely worth a read.
Fraser said:
Everyone talks about code smells but no one ever describes what they smell like Fish? Wet dog? Or something rich and vibrant like peach syrup or the smell of dirt after it rains.
Fraser said:
Everyone talks about code smells but no one ever describes what they smell like Fish? Wet dog? Or something rich and vibrant like peach syrup or the smell of dirt after it rains.
It comes up occasionally For example, I’m configuring Apache eCharts for some reporting software I’m working on.
To style these charts, I need to set colors, font sizes, etc. through Javascript So it’s helpful to link them to the CSS variables like the rest of the system.
Or maybe you face one of those tricky CSS problems where you’ve tried everything but have to fall back on Javascript for layout - and that JS needs the CSS variables.
You won’t need this often but sometimes it’s necessary.