CSS Variables with Global & Local Scope
Hello everyone!
I've not posted anything about CSS yet. I am an aspiring Front-end Developer and suddenly realised I had forgotten many CSS basics. So, I started learning it once again.
This post is about CSS Variables.
Here I learned the usage of CSS variables and how you can use them in your project.
First of all, a CSS variable name must start with two dashes -- and it is case-sensitive.
For example:
--blue: #1e90ff
--red: rgb(255,0,0);
Global & Local Scope
Declaring Global CSS Variable
CSS Variables can have a global scope and a local scope. When you declare a CSS variable in a global scope, it can be accessed throughout the entire document.
To create a variable with global scope, we need to declare it inside the :root selector. The :root selector matches the document's root element. We declare a global CSS variable as follows:
Recommended by LinkedIn
root: {
--blue: #1e90ff;
--red: rgb(255, 0, 0);
--white: #ffffff;
}
Using CSS Variable in Local Scope
To create a variable with local scope, we need to declare it inside the selector that is going to use it.
The var() function is used to insert the value of a CSS variable. The syntax of the var() function is as follows:
var(name, value);
To use the above declared global variables inside another selector we need to write it in the following way:
body {
background-color: var(--blue);
color: var(--white);
}
button {
background-color: var(--white);
color: var(--red);
border: 1px solid var(--red);
}
The usefulness of CSS Variables
I hope you have learned something new by reading this blog. Thank you so much for your valuable time.
Happy Coding! Happy Learning!!
Front-end Developer | MERN Stack Aspirant | Exploring RPA | UiPath | Coding | Automation
1yThank you brother Very useful information ☺️