CSS Variables

These variables of CSS are applied to add the custom property values to our various web-pages. The custom properties are often called as CSS variables or cascading variables. Various authors portray these items because they include specific values or may be recycled throughout any document. These items are set with the use of the notation of custom property and may be authorized with the help of var() function.

These variables reserve multiple values, and contain a scope where it can be used.

The variables of CSS are advantageous as they permit to reuse any similar value over multiple positions. The variable name is efficient to use and understand, unlike the value of the color.

Syntax:

A CSS variable is specified with the use of two dashes (–) in the starting, pursued by a case-sensitive name.

The element shows a selector that describes the custom property’s scope, in the above-described syntax. If we depict a custom property over a pseudo-class: root, this class will be applied to the HTML document globally. The custom properties names are case-sensitive, like –Main-color and –main-color will be evaluated as a separate custom attribute.

var() function

This CSS function is applied to add the value of the custom property. The variable name may be passed the same as an argument to a var() function.

Syntax:

Parameters

The function var() allows only two arguments as below:

–custom-name: It accepts the custom property name. This parameter should start with two dashes (–). This parameter is a required parameter.

Value: This parameter is the optional parameter. It allows for any fallback value. If any custom property will be invalid, then this parameter will be used as a substitution.

The fallback value is not applied to fix-up the compatibility of the browser. These values are not advantageous when the browsers do not provide their support to any custom properties. This value implements as a substitution for any browser, i.e., offers its support for custom properties of CSS for selecting any distinct value if a variable isn’t depicted or if any variable contains any invalid value.

A few invalid or valid ways to illustrate these fallback values are mentioned as below:

Let’s take some illustration to understand the concept of CSS variables.

Example:

Output:

CSS Variables

The above example is not defined with the fallback values. Consider the below example:

Example:

In the following demonstration, here we use –text-color CSS variable. These fallback values are used as a variable substitution because the variable –text-color is not set.

Output:

CSS Variables

var() with the Calc()

We can apply the calc() function over the values of the variables. In the following demonstration, we are using the var() function with the calc() function.

We are applying the var() function with the calc() function to maintain the font-size and padding of any element.

Example:

Output:

CSS Variables

Pin It on Pinterest

Share This