DEV Community

Cover image for CSS Variables with Global & Local Scope
Swarnali Roy
Swarnali Roy

Posted on

CSS Variables with Global & Local Scope

Hello everyone!
It's been a long long time since I've posted anything. I am working as a Front-end Developer and suddenly, I realized that I have forgotten many CSS basics. So, I started learning it once again.

This blog 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);


Enter fullscreen mode Exit fullscreen mode

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;
}


Enter fullscreen mode Exit fullscreen mode

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);


Enter fullscreen mode Exit fullscreen mode

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);
}

Enter fullscreen mode Exit fullscreen mode




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 used CSS Variables in a FreeCodeCamp Learning project to change the colors of my design and it came out like this:

City Skyline Day

City Skyline Night

You can have a look at the code by accessing this repo:
https://github.com/SwarnaliRoy94/FreeCodeCamp-CSS-Projects/tree/main/CSSVariablesSkyline

I hope you have learned something new reading this blog. Thank you so much for your valuable time. Feel free to ask me anything in the discussion section.

Happy Coding! Happy Learning!!

Top comments (0)