CSS Cover Variables
- Previous Page CSS Variables
- Next Page CSS Variables - JavaScript
Overriding global variables with local variables
From the previous page, we learned that global variables can be accessed/used throughout the entire document, while local variables can only be used within the selector they are declared in.
See the example on the previous 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; }
Sometimes, we want the variable to change only in a specific part of the page.
Suppose we want the button element to use a different blue. Then, we can redefine the --blue variable within the button selector. When we use var(--blue) in this selector, it will use the value of the locally declared --blue variable here.
We can see that the local --blue variable overrides the global --blue variable of the button element:
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 { --blue: #0000ff; background-color: var(--white); color: var(--blue); border: 1px solid var(--blue); padding: 5px; }
Add a new local variable
If a variable is used only in one place, we can also declare a new local variable, like this:
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 { --button-blue: #0000ff; background-color: var(--white); color: var(--button-blue); border: 1px solid var(--button-blue); padding: 5px; }
Browser Support
The numbers in the table indicate the first browser version that fully supports this property.
Function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
CSS var() Function
Function | Description |
---|---|
var() | Insert the value of the CSS variable. |
- Previous Page CSS Variables
- Next Page CSS Variables - JavaScript