How to use variables in CSS coding?

Use of variable in CSS coding gives us the power to change the global setting of particular parameters. The use of variables is very simple in CSS coding.

Let us see how to do this…

Suppose you have to change some styles globally for number of different values in CSS.

So for that we shall write three variables first in CSS file at the top (for reference purpose), as follows. To create global variables, declare them inside the :root selector. The :root selector matches the document’s root element.

:root {
	--primary-color: #ee4455;
        --secondary-color: #75dd33;
        --third-color: #f7f7f7;
}

After creating the variables inside :root selector, you can write var(name) function inside your stylesheet anywhere you like, as shown below.

h2 {
	color: var(--primary-color);
}
h2 { 
        border-bottom: 2px solid var(--secondary-color); 
}
.box {
        background-color: var(--third-color);
        padding: 20px;
}

Now whenever you want to change the styles you just have to change the values of variables in :root selector, that’s all…! It will affect globally on your website.

Isn’t it simple enough? Hope you liked it…!

If you have any queries, please write your comment below.

Share on your network!
Prof. Dattaraj Vidyasagar
Prof. Dattaraj Vidyasagar

Author on this website. He is veteran of Core Electronics since last 36+ years. ATL Mentor of Change, Niti Ayog, Govt. of India, Google Certified Educator, International Robotics Trainer and author of 18 books on electronics, robotics, programming languages and web designing... ➤➤

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x