Site icon NodeXperts

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 begun 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 to start with two dashes.

value

This is an optional field

Example 1: How can we declare CSS Variable

: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 color can be used multiple times, and if we want to replace the color, it is possible to search color and replace it everywhere. But if we are using CSS Variable, we can define the value globally and replace it everywhere. We need to define variable globally and call it.

CSS Variable Fallback Values

When using CSS Variable, we can define more than one fallback value when the variable is not restricted. The First argument is the name of the custom property need to substitute. The second argument, if defined, is the fallback value, which is substituted 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” */

Exit mobile version