CSS Variables var() Function

CSS Variables var() Function


CSS Variables var() Function
CSS Variables allow authors to create reusable values which can be used throughout a CSS document. 
For example, it's common in CSS to reuse a single color throughout a document. 
Prior to CSS Variables, this would mean reusing the same color value many times throughout a document. 
With CSS Variables the color value can be assigned to a variable and referenced in multiple places. 
This makes changing values easier and is more semantic than using traditional CSS values.
Note -
As Usual like variables in any programming language variable has scope.
They are case sensitive.
var() - 
Syntax - 
var(--name, value)
 
Explanation - 
  1. Name -  This is used to specify name of variable
  2. Value  -  This is used as a fallback value.
Now we will see an Example - 
Example - Inheriting a parent’s variable - 
<style>
.container {
--heading-color: blue;
font-family: Arial, sans-serif;
}
.container h1 {
color: var(--heading-color);
}
</style>
<div class="container">
<h1>Welcome</h1>
</div>
Output -

 
Example 2 -  Referencing variables inside other variables -
<style>
:root {
--primary-border-color: red;
--primary-border-style: solid;
--primary-border-width: 3px;
--primary-border:
var(--primary-border-width)
var(--primary-border-style)
var(--primary-border-color);
}
.container {
border: var(--primary-border);
width: 10rem;
}
</style>
<div class="container">Hello World!</div>
Output -