As discussed in the previous section, global variables are available for use across the entire document, whereas local variables are confined to usage within the selector where they are defined.
Refer to the example provided on the preceding page.
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; } |
At times, we may desire variable changes to apply solely within a specific section of the page.
For instance, if we wish to assign a distinct shade of blue to button elements, we can redefine the –blue variable within the button selector. Consequently, when utilizing var(–blue) within this selector, it will utilize the locally declared –blue variable’s value.
This demonstrates that the local –blue variable takes precedence over the global –blue variable for button elements.
Example
:root { |
If a variable is intended for use in only one specific location, we could alternatively declare a new local variable, as shown below:
Example
:root { |
The numbers in the table indicate the initial browser version offering full support for the var() function.