CSS3 Variables

Learn via video course
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
Start Learning


CSS3 comes with a variety of new features and components like animations, responsiveness, etc. It helps programmers to write CSS in an easy way. One of the features that CSS3 offers us is to create Variables. That's right, even though CSS is not a programming language, you can create Variables and use them all over in your CSS code. Thanks to CSS3.

What are CSS Variables?

Variables can be defined as an entity that is capable of storing values. Values can be anything that you give to your CSS properties. You can store any type of data(like string, number, characters) inside this variable. These variables require some memory; hence variables were generally created for programming languages like JavaScript, Python, C++, etc.

Now, CSS is not a programming language (It is used for styling HTML elements), but that doesn't mean you cannot create a variable here. CSS3 has introduced us to a way where you can actually create a variable in CSS.

CSS variables are ideally custom properties that allow you to store a value in it and use it anywhere in your CSS code. So instead of providing value to the CSS property, you can just provide the variable which will be storing that value.

In this, you can not only store values in CSS variables but using JavaScript, and you can actually manipulate or change data accordingly.

Syntax of Var Function : Declaration and Initialization

Every variable must have to go under two processes -

DeclarationDeclaring a variable by assigning it a name
InitializationSpecifying a particular value to the variable

Note -

  • Since CSS is used on the browser, CSS variable does not allocate any memory in your local storage. It uses browser memory.
  • Also, if you don't initialize your CSS variable, the browser will not give you any error.

To declare a variable, you have to use the"- -" prefix in front of the variable name. Let's see the syntax -

Here var-name is your variable name, and it is case-sensitive, while value is the data for your variable.

Example -

This will create a my_font variable, and now you can use it anywhere in your document. Also, you cannot initialize your variable anywhere else, and you have to initialize it right when you declare.

Now here comes another question. How can you use a variable in CSS after declaring?

CSS3 has provided you with a function var(). This function will allow you to pass your variable name as a parameter to this function, and also you can pass the value of your variable as well (as a parameter).

Let's see the syntax -

var_nameThis is a required parameter and defines the name of your variable
valueThis is an optional parameter and defines the value of your variable

Example -

How var() Works?

The above syntax that we used is not highly recommended because we are just increasing the complexity of a simple CSS property.

For example, let's say I want to give a paragraph a size of 20px. I will use the property "font-size" and then assign the value like this -

I can also use the var() function for this -

Both of them will do the same thing. Now let me ask you another question. Can we use the same variable font_sizein other paragraphs inside the document?

The Answer is NO. Here comes the concept of SCOPE.

Every variable has a scope that defines the accessibility of that variable. In CSS, every variable has two types of scope -

  • Local
  • Global
LocalIf the variable is declared inside a selector, it is called a Local Variable. It will be accessible inside that selector only.
GlobalIf the variable is declared inside the : root selector, it is called a Global Variable. It will be accessible throughout the document.

So I think you now understand why we cannot use the variable font_size for other elements because it was declared inside the p selector.

Let's see how to declare and use a Global Variable. As discussed earlier, Global Variables are declared inside the : root selector, but what exactly is : root?

Root Selector

: root selector in CSS is a pseudo-class that identifies the root element of your HTML document. html and : root both of these selectors are the same. They are used to select all the elements present in your documents, except for the fact that : root has a higher priority than the html selector.

If you add any CSS property inside the : root selector, the selector will make every property available to all the elements inside the page. Hence if we declare a variable here, it will be accessible to all the elements. That's why the term Global Variable.

Let's see one example of creating and using a CSS Global Variable -

  1. Create a variable inside the : root selector. Don't forget to add "--" as a prefix to your variable name.
  1. Your variable is now created. In order to use it anywhere, you have to use the var() function and pass the variable name as the parameter.
  1. Following is the output of the above code. It will help you understand more.

As you can see, we created two variables here -

Using the var(), we have used those two variables to change the color of the headings.

Importance of CSS Variables

  1. Eliminate Code Duplication.

Let's consider a scenario. You have to build a small website that contains some headings and some paragraphs. Now for headings, you need to give them a red color, and for paragraphs, you need to give them a blue color.

I'm sure your code will look like this -

Now, I want to change the heading to green, and I have to change red to green in every possible place. This will just decrease your productivity. That's when variables come in handy.

Using variables, you just have to change the value of the variable, and it will get assigned to every possible place where you were using that value.

  1. No usage of Preprocessors.

Preprocessors are used to compile your variables whenever you create a variable or change its values. Like in Java, the compiler is responsible for creating and changing variables. In the same way before CSS3, preprocessors like SASS or LESS were used. But in CSS3, we don't need to use preprocessors since we can easily create and change variables here.

  1. Incredibly Flexible.

CSS variable are so extremely versatile. You can declare it anywhere inside your code. If you want to change the size of text, you don't have to change all the values where you defined it. You just have to change the value of the variable, and done.

You can use it inside the <style> tag. Or you can even declare your variable as an inline styling in your HTML document.

  1. Code readability has increased.

For Programmers, code readability is the most important part while reviewing any code snippet. The greater the code readability is, the faster the programmer is able to solve the bug. Variables in CSS allow them to read the code effectively and appropriately.

Consider below code snippet -

I have given an rgb value color to the heading. Now at the end of the code, I have given the same color to a particular class selector -

Now the developer will have to check if the color is the same or not by scrolling up and down. What if this is happening for the other 20 scenarios? This will just decrease the programmer's productivity.

Hence using a variable will help the user determine which color is used by just seeing the variable name. This will help increase the code's readability.

Calc and CSS Variable

CSS gives us another special function called calc(), which is used to perform basic calculations with the values. It requires two parameters and one operator. Let's see the basic syntax of calc() -

Calculate can take any of the following units of values.

calc and css variable

calc() function is very important for those who like to set things with respect to other elements inside a webpage. Many times we want to maintain the width of a container even when the size of the screen changes. That's when calc() comes in handy. You calculate the width with respect to the screen size and assign it to the width property. That's why you need to understand how to use calc().

You can use CSS variable inside this calc() function as well. This will allow you to handle the positioning of elements properly.

Let's see one example

You can see that the heights of both rectangles are different. The base height is the same for both of them (--height:4em). Using calc(), we are adding values to them, which will increase the height accordingly. You can add, subtract, multiply or divide any value as per your will.

Scope in CSS Variables

We have learned earlier the scope of CSS variables. Let's understand them in depth. There are two types of scope for variables in CSS -

1. Global Scope
2. Local Scope

  1. Global Scope - Declare once, use anywhere.

Global scope's variables are accessible through the code. You have to declare it once, and you can use it anywhere in your whole CSS document. You just have to declare your variable inside the : root pseudo selector. Any variable declared inside the : root selector is treated as a global variable. Following is the syntax for a global variable.

  1. Local Scope - Accessible inside selector boundaries.

Local scope variables are accessible inside the selector where it is declared. You cannot use the variable outside its selector walls. Suppose you declared a variable inside a class container. Then you can only use that variable inside the container class and not outside it.

Following is the syntax -

Precedence And Inheritance

Till now, we know how to declare a local variable and how to declare a global variable. But what if we declared both of them with the same variable name and used them inside the same scope? Let's find out.

Consider the following piece of code -

As you can see from the output above, none of the divs have got blue background color. The first div has green color since we have created a local variable inside it (--bg-color). And the second div gets the color from the global variable(i.e., red). Hence we can say that Global Variable has less precedence than the Local Variable.

We know from other programming languages that inheritance is nothing but the process in which the child class can access the members of the parent class. In CSS, it is the Child element and Parent element. Declaring an element inside another element creates a relationship between them which is called as inheritance.

Let's understand a complex example -

As you can see, Class A is the Parent Element. Class B is the Child Element to Class A but also a Parent Element to Class C. And finally, Class C is the Child element in both of the Classes(A and B).

Now when you apply styling to the parent element, the child element also gets the same styling. This is what confuses many programmers. See the following code snippet.

As you can see, First Div is the Parent element. Second Div is the Child element for First Div and the Parent element for Third and Fourth Div. Lastly, Third and Fourth Div are the child element of both First Div and Second Div.

We know that the child element gets the styling of the parent element. So since the Parent element(first div) has a yellow background color, Second div also has the same color, and Fourth div (child of a second) also gets the same color.

Third div (child of the second div) does not get the same yellow color. Why?

Because we declared a local variable --my-bg and gave it a color green. And we know the local variable has a higher priority than the global variable. It takes the background color as green.

Fallback Values In CSS Variables

Fallback Values can be termed as the backup values in CSS Variables. Fallback values are generally the second parameter of the var() function. They are used to add additional value to your variable and use it on the same property. This value is optional.


Example - Let's consider we have a rectangle which background we would like to change with the variable --color;

If we have not yet initialised this variable previously, this rectangle will take this Grey color as the background. This is Fallback Value.

Now consider some of these rectangles have a class of name .inside-rectangle. Here we can specify the background color as Purple.

In this way, fallback values are used. Rectangles with .inside-rectangle classes will have a purple color, while the rest of the rectangle will have the grey color.

Exceptions in CSS Variables

You now know how powerful and easy CSS variables are. But there are a few exceptions you must know before using them in your Projects.

  1. Never make a Cycle of Dependencies.

Dependencies are created when one element's execution is solely dependent on another element. Whenever you try to create any dependency, you should try not to create a cycle among the variables.

Let's say, for example, you are waiting for your friend John to pick you up, and John is waiting for his friend Chris to pick him up. At the same time, Chris is waiting for you to pick him up. This creates a Dependency Loop. See the following code snippet -

As you can see, variable-1 is dependent on variable-2 and variable-2 is dependent on variable-1. This creates an infinite loop which results in an infinite load on our website.

  1. Variables are Case-Sensitive in CSS.

Remember, like in any other programming language, CSS variables are case-sensitive. Means variable and Variable are both different.

  1. Property name shall not be used as Variable name.

You can give any name to your variable, but you have to make sure that it's not the same as an existing property name. You cannot declare a variable with the name --background-color because it's a property name.

Browser Compatibility of CSS Variables

CSS variables are widely supported by the majority of browsers. Below is the list of browsers and their versions that supports var().



  • Variables can be defined as an entity that is capable of storing values.
  • CSS variables are ideally custom properties that allow you to store a value in it and use it anywhere in your CSS code.
  • To declare a variable, you have to use the “” prefix in front of the variable name.
  • In CSS, every variable has two types of scope -Local and Global.
  • CSS Variables eliminate Code Duplication, are incredibly flexible, and increase the readability of code.
  • calc() function is used to perform basic mathematical calculations.
  • You can use CSS variable inside this Calc() function.
  • Global Variable has less precedence than the local variable.
  • Fallback Values can be termed as the backup values in CSS Variables.
  • CSS variables are widely supported by the majority of browsers.