Nishant

Frontend Developer Software Developer || Fascinated by tech trends || Building usable systems that work on web and mobile.

CSS Variable

css variable

CSS Variables can be declared in a CSS Selector to define the CSS Scope. For use Globally we can use body selector or :root. The CSS Variable must be begin with dashes like (–), and css variable is case sensitive.

The CSS Variable syntax:

var(custom-name, value)

custom-name

: This is a required field. It requires any name start with two dashes.

value

: This is a optional field

Example 1: How can we declare CSS Vairable

:root {
--main-bg-color: coral;
}

#div1 {
background-color: var(--main-bg-color);
padding: 5px;
}

#div2 {
background-color: var(--main-bg-color);
padding: 5px;
}


#div3 {
background-color: var(--main-bg-color);
padding: 5px;
}

The Output of this code is :

Why CSS Variable?

Some Websites such as: E-Commerce, have large CSS codes, with a repeated value most of the time, For Example: Same colour can be used multiple times, and in case we want to replace the colour then it is possible to search the colour and replace it everywhere. But if we are using CSS Variable then we can defined the value globally and it replace it everywhere. We just need to defined variable globally and call it.

CSS Variable fall back values

When we are using CSS Variable, we can define more than one fallback values, when the variable is not defined. The First argument is the name of custom property need to subsituted. The second argument, if defined is the fallback value, which is subsituted when the first argument is invalid. For Example

.two {
  color: var(--my-var, red); /* Red if --my-var is not defined */
}

.three {
  background-color: var(--my-var, var(--my-background, pink)); /* pink if --my-var and --my-background are not defined */
}

.three {
  background-color: var(--my-var, --my-background, pink); /* Invalid: "--my-background, pink" */
Share