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.

Dr. Dattaraj Vidyasagar
Dr. Dattaraj Vidyasagar

M.S. Electronics & Telecomm. (Cleveland Institute of Electronics, Ohio), Associate Member (IETE, Kolkata), Panelist on Dr. Homi Bhabha Foundation, Google certified educator (Level-1), Mentor of Change (MoC-1619) Niti Ayog, Government of India, International Robotics Trainer, Veteran of Applied Electronics since 35+ years.

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