How to create variables in CSS ?

zahra kaabi
2 min readMay 9, 2021

--

CSS variables, known as CSS custom properties, are very useful for reducing repetition in CSS, and also for powerful runtime effects like theme switching and potentially extending/polyfilling future CSS features.

How we use variables ?

Now, let’s first understand how CSS variables works (global vs local variables):

Global variables can be accessed or used through the entire document, while local variables can be used only inside the selector where it is declared.

The easiest way to create variables with global scope is by declaring them into the :root pseudo-class.

In order to use the value of the CSS variable, we can use the var() function as you can see it in the image above (variables with local scope, must be declared inside the selector that is going to use it).

Does browsers support var() ?

Well, CSS variables are now supported in all modern browsers, but you can verfy it by visiting out can i use website.

Why we need to use CSS variables ?

Now, you are familiar with it but why should i use it in my code you may ask yourself. Well, imagine this scenario: “You’ve just finalized the latest draft of your website. Everything works as planned, and suddenly you received an e-mail from your boss telling you to change that purple color that you used it in multiple places in your code by red”.

It seems not handy to open all CSS files and change the color. Right?

Here is why we use CSS variables, instead of copy and paste the same colors over and over again, you can place them in variables.

--

--

No responses yet