Skip to main content

Override Global Variable With Local Variable

Global variables can be used anywhere in the document, while local variables can only be used inside the selector where they are declared.

Sometimes you want a variable to change only in a specific part of the page.

To do this, you can re-declare the variable inside a more specific selector. When you use var() inside that selector, it will use the local value instead of the global one. The local variable overrides the global variable for that selector.

Example

Here, the .note selector re-declares --primary-bg-color as red. Inside .note, the local value is used instead of the global blue.

Prompt
Create a page with CSS variables. Define --primary-bg-color (#1e90ff) and --primary-color (#ffffff) in :root. Set the body background to --primary-bg-color. Add a .container with text color --primary-bg-color, white background, and padding. Give .container h2 a bottom border using --primary-bg-color. Inside .container, add a .note element that re-declares --primary-bg-color as red (overriding the global), and uses it for a 1px solid border with 10px padding.
Output: complete HTML page

Add a New Local Variable

If a variable is only going to be used in one place, you can declare a brand new local variable instead of overriding the global one.

Example

Here, a new local variable --note-border-color is declared inside .note and used only for that element's border.

Prompt
Create a page with CSS variables. Define --primary-bg-color (#1e90ff) and --primary-color (#ffffff) in :root. Set the body background to --primary-bg-color. Add a .container with text color --primary-bg-color, white background, and padding. Give .container h2 a bottom border using --primary-bg-color. Inside .container, add a .note element that declares a new local variable --note-border-color as red, and uses it for a 1px solid border with 10px padding.
Output: complete HTML page