loading

Overriding Variables

Override Global Variable With Local Variable

As we saw on the previous page, local variables can only be used inside the selector in which they are declared, whereas global variables can be accessed and used throughout the document.

Examine the preceding page’s example:

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;
}
				
			

Occasionally, we would like the variables to just alter in a particular area of the page.

Assume that the button elements should have a different shade of blue. The –blue variable can then be re-declared inside the button selector. The local –blue variable value declared here will be used when we utilize var(–blue) inside this selector.

For the button components, we can observe that the local –blue variable will take precedence over the global –blue variable:

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; /* local variable will override global */
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}
				
			

Add a New Local Variable

We might have also defined a new local variable, such as this, if a variable was only going to be used once:

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; /* new local variable */
  background-color: var(--white);
  color: var(--button-blue);
  border: 1px solid var(--button-blue);
  padding: 5px;
}
				
			

Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

Overriding Variables -

CSS var() Function

Property Description
var() Inserts the value of a CSS variable
Share this Doc

Overriding Variables

Or copy link

Explore Topic