CSS Variables with Global & Local Scope

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:

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

  1. CSS variables have access to the DOM, so we can create it with both global and local scope.
  2. It can be changed with JavaScript.
  3. It can be changed based on media queries.
  4. The best way to use CSS variables is to change the color properties of your design. You can declare some variables and use them over and over again instead of copy-pasting the same colors.



I hope you have learned something new by reading this blog. Thank you so much for your valuable time.

Happy Coding! Happy Learning!!

Roshan Rawat

Front-end Developer | MERN Stack Aspirant | Exploring RPA | UiPath | Coding | Automation

1y

Thank you brother Very useful information ☺️

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics