What are CSS Variables? Explain with Example

Variable is used in programming languages such as C, C++, JS, Python, etc. to hold values that have to be used in the entire program. In a website to use variables, we have to use CSS Variable concept.

CSS Variable introduced in CSS3 version, it is an advanced property of CSS which help us to manage our repeated code easily.

CSS Variable is used to keep the common property of website which is used in multiple pages of the website such as background color, font style, font size, etc.

If we keep common CSS property in a variable we can manage easily by changing root value only, there is no need to change property in different places.

Syntax:

:root
{
  --css-variable-name:css-property-value;
}
 

Example:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
:root
{
   --grey-color:#eee;
   --red-color:#f00;
}
 
.main
{
  width:100%;
  height:1000px;
  background:var(--grey-color);
}
 
.box
{
  width:400px;
  height:400px;
  background:var(--red-color);
}
 
.box h1
{
  color:var(--grey-color);
}
 
</style>
 
</head>
 
<body>
 
<div class="main">
 
<div class="box">
<h1>CSS Variable</h1>
</div>
 
</div>
 
</body>
</html>
 

In this example, --grey-color variable is used in .main class for background color and in .box h1 for h1 font color.

CSS variable is helpful if you want to reuse your website template or website component because in CSS Variable we can change CSS property by just changing root value.

Categories: web designing css

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 20 Days

Crash : 7 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 7 Month

Fastrack : 4 Month

Crash : 2 Month

Related Blogs

Request For Demo