CSS variables are used to store a value that can be used frequently in the HTML document.
The variables are defined by a name preceded by double dash and value is assigned to the variable after a colon. Example: --my-color: teal;
Defining a Global CSS variable
The variable is defined in a way mentioned above.
Now, to access the variable and to use it in the HTML document we use var() function. Example: color: var(--my-color);
Using CSS variable
CSS variable scope
Any variable that we define in CSS has a scope value. Beyond a variable's scope is not accessible.
We have two type of scope :
- Global scope
- Local scope
1.) Global scope
A variable which is defined globally can be accessed anywhere in the linked document.
A global variable is defined inside :root selector.
2.) Local scope
A variable is defined locally by defining it within the code block of a specific selector.
A local variable can only be used within the selector it is defined.