Curriculum
Course: CSS Advanced
Login

Curriculum

CSS Advanced

CSS Rounded Corners

0/1

CSS Border Images

0/1

CSS Color Keywords

0/1

CSS Text Effects

0/1

CSS 2D Transforms

0/1

CSS 3D Transforms

0/1

CSS Transitions

0/1

CSS Animations

0/1

CSS Tooltip

0/1

CSS Style Images

0/1

CSS Image Reflection

0/1

CSS Masking

0/1

CSS Buttons

0/1

CSS Multiple Columns

0/1

CSS User Interface

0/1

CSS Box Sizing

0/1

CSS Media Queries

0/1
Text lesson

Overriding Variables

Override Global Variable With Local Variable

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 {
  –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

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 {
  –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 indicate the initial browser version offering full support for the var() function.

IMG_3707