CSS Variables

CSS variables: they are very useful when you repeat the same value over and over in your style sheet.

Declare your variable once, and then call it as many times as you want. Where could this be more useful than in designing a color- theme?

For example you could use your variable for the border AND for the font color AND for the background.

This is how you declare your variable:

--myColor: blue;

And when you call it, you do it this way:

p {
color: var(--myColor);

You can even make a variable made of other variables! See this example from my demo:

--red: 125;
--green: 125;
--blue: 255;
--mainColor: var(--red), var(--green), var(--blue);
--secondaryColor: var(--blue), var(--red), var(--green);

(I used this in rgb format in the demo below)

You can say, well, we already have preprocessors variables. But what’s different and very interesting with CSS variables is that you can update it with css without having to reload the page!

animated gif of a project demonstrating CSS variables used for colors
animated gif of a project demonstrating CSS variables used for colors

To demonstrate this, I made this little demo for school. A big Thank you to Ohans Emmanuel who wrote a very complete introduction to CSS variables here.

Published by

Aurelie Bayre

Hello! My name is Aurelie Bayre and I am a webdeveloper living in France.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.