CSS Variables changed my Life! π
Β
Hi, *|USERNAME|*!
One of the biggest improvements made to CSS in the past few years isn't richer layout viaΒ Flexbox or Grid. It isn't even better animation support. It is something far more subtle. It is support for CSS Custom Properties, commonly also known as CSS Variables.
Just like with variables in the JavaScript world, CSS variables allow you to define a variable and assign it a value:
:root {
--logoColor: "#333";
--headerColor: "green";
--avatarWidth: 150px;
}
Once you've setup your variable, you can then use it in places where you'd normally hard-code a value:
#avatar {
width: var(--avatarWidth);
height: 350px;
background-color: var(--logoColor);
display: flex;
}
Just like with variables you wouldΒ use in JavaScript, you now have a single location where the value is being specified. If you change the value of any of our CSS variables, any uses of it will use the new value as well. That's pretty awesome, for it now allows you to do things more easily that would have been very difficult to do in the past. One such thing is being able to more easily modify CSS values via JavaScript. This allows you to do something almost unheard of in CSS, such as animating circular stripes:
If you take a look at the code, you'll notice that the stripe colors are defined as CSS variables. The animation involves not just changing the shape of the gradient, but also swapping all the colors when the gradient reaches a certain point. With CSS variables, this is a simple enough to do. Without it, we'd be generating and re-generating a lot verbose gradient-related values entirely as strings in JavaScript. That is never fun.
TILL NEXT TIME!
Not all improvements need to be brand new and unlock new scenarios. Sometimes, improvements that simplify what used to be painful should be celebrated as well. CSS variables fall within this bucket. What do you think? Have you used CSS variables yet and found it a major productivity booster as well? Drop by the forumsΒ and chime in or simply ping me via Twitter.
Cheers,
KirupaΒ π