CSS variables offer access to the Document Object Model (DOM), enabling the creation of variables with either local or global scope. They can be modified using JavaScript, and their values can be adjusted based on media queries.
A practical application of CSS variables is in managing color schemes within your design. Rather than repeatedly copying and pasting the same colors, you can define them as variables for easy reference and maintenance.
The following example demonstrates the conventional approach to specifying colors in a style sheet by explicitly defining the colors for each specific element.
Example
body { background-color: #1e90ff; } h2 { border-bottom: 2px solid #1e90ff; } .container { color: #1e90ff; background-color: #ffffff; padding: 15px; } button { background-color: #ffffff; color: #1e90ff; border: 1px solid #1e90ff; padding: 5px; } |
The var() function is employed to incorporate the value of a CSS variable, with the following syntax:
var(–name, value) |
Value |
Description |
name |
Required. The variable name must start with two dashes. |
value |
Optional. The fallback value, used if the variable is not found. |
Please note: Variable names must start with two dashes (–), and they are case-sensitive.
Firstly: CSS variables can possess either global or local scope.
Global variables are accessible and usable throughout the entire document, whereas local variables can only be utilized within the selector where they are declared.
To establish a variable with global scope, define it within the :root selector. The :root selector corresponds to the document’s root element.
To establish a variable with local scope, define it within the selector where it will be utilized.
The following example mirrors the previous one, but it employs the var() function.
Initially, we declare two global variables (–blue and –white). Subsequently, we utilize the var() function to insert the values of these variables elsewhere in the style sheet.
Example
:root { –blue: #1e90ff; –white: #ffffff; } body { background-color: var(–blue); } h2 { border-bottom: 2px solid var(–blue); } .container { color: var(–blue); background-color: var(–white); padding: 15px; } button { background-color: var(–white); color: var(–blue); border: 1px solid var(–blue); padding: 5px; } |
The benefits of utilizing var() include:
To transition from a vibrant blue and white to a softer blue and white, adjusting the values of the two variables is all that’s required.
Example
:root { |
The numbers in the table indicate the initial browser version offering complete support for the var() function.