What are CSS variables?
Nazanin Ashrafi
Posted on December 5, 2020
If you google What are CSS variables? you'll get answers such as this one :
"Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document"
To be honest this definition of CSS variables was too confusing for me! like what does that even mean?!
In this article I'm gonna try to simplify it for you.
Here I created a lot of simple shapes with just two colors : pink and powderblue.
P.S I could just use class="circle"
or class="square"
instead of writing too much codes , but it's just an example , I'm only trying to you show how CSS variables works
So there are lots of
background-color: pink;
(you can also check the CSS section in pen)
background-color: powderblue;
If I were to change the color to something else I had to change the background-color
one by one
It would take so much of my time
BUT instead of doing so, we can create a CSS variable for it
Now the question is how to write a CSS variable?
We can do so with the help of pseudo-class, like this :
:root {
--variable's name : property;
}
By declaring a custom property the change will be applied throughout our HTML document
Let's write our code with a variable and apply it to our page
:root {
--square-color : red;
}
.Square {
background-color: var(--square-color);
}
If you change the variable's color from red to any color of your choice, all of the square's color will change and it will save you a lot of of time.
You can play around and experiment with the pen to understand it better.
I've made another pen just to show, you can use other property as well :
Posted on December 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.