A comprehensive guide to CSS Variables
(commonly known as CSS variables) #
I started using CSS variables when i came across them while building a loader. They are amazing!. In simple terms, they are variables prefixed with --, and can be used by putting them in a
var() function.One of the best reasons to use CSS variables is that they reduce repition.You can use them like this:
Further in this article ,we will call them CSS variables. #
Some important points : - #
- CSS variables are scoped to the element they are declared.
- They are case sensitive,i.e:
--BgColorwill be two different CSS variables.
- CSS variables are not actually variables as in programming languages, they will be set only in the elements they are applied on.
CSS variables can be used in many ways, and should not be limited to just use them as variables. There can be many interesting use cases and i'll discuss the ones which i have come across so far.
Use cases #
- Animating Pixel art #
- Making tints and shades #
- Global and Component scoped styles #
- Dark/Light Mode #
and many more... #
Animating Pixel art #
If you like to make your pixel art with
box-shadow, animating or even changing the values can be really hard because there are so many box-shadows that rewriting them again and again in
@keyframes can be tiring. Instead of writing box-shadow values again and again,we can use css variables.I made a Calavera pixel art on Codepen and changed the css variables in my
Making tints and shades #
If you don't know what tints and shades are, you can learn about it in basic color theory. I'll explain here in simple terms:
- Choose a color. Let's say blue, now the tints would be the lighter versions of blue, and the shades will be the darker versions.
So, to make tints and shades easily, we can use css variables. We will use
hsl() for our colors, as we will change the lightness in HSL(hue, saturation, lightness).
The idea is to use
hsl() on the main color for which we want the tints and shades,and change the lightness by using css variables.
As you can see, I made two variables
--main-color , and
--lightness , and set different classes for different tints and shades. Then i changed the
--lightness variable in each tint and shade, and therefore we can see different colors as their lightness is different!
Global and Component scoped styles #
Global css variables can be declared by putting them in a
:root selector. Sara Soueidan has a great article on this which will give you more insight into this particular use case.
Dark/Light mode #
We can also implement Dark and Light mode by using css variables. Ananya Neogi has a wonderful article on this implementation.
So I guess that's it! I hope you got a teeny tiny idea of what css variables are and what they can do. If this helped you, you can drop a comment here.