CSS Variables
Like basic variables in any other programming language, CSS variables are also simple variables. These variables have a range in which they can be used and are used to store values. A variable is defined by starting it with two dashes (-)
, followed by the name, which is case-sensitive. The advantage of variables is that they make it possible to update/modify values from a single location while reusing the same values elsewhere. In addition, the variable names are simpler to comprehend and use than the color values since they eliminate the need for repetitive copying and pasting of color values.
Syntax
The values of the CSS variables can be obtained using the var() function.
Parameters: The two parameters that the variable var() accepts are as follows
- custom-name: The mandatory argument custom name accepts a custom property name that begins with two dashes(-).
- value: It is a choice-based parameter. If a custom property is invalid, it accepts a fallback value.
Working of CSS var() function: In CSS, variables can have either a local or global scope. The local variable can only be used inside the selector where the variable is declared, within the scope, as opposed to the global variable, which may be used throughout the entire text. We must declare the variable inside the: root selector, where it compares for the document's root element, in order to create variables with global scope. We can declare the variable inside the selector, where it can be utilized within the scope, to create it in the local scope.