Like other CSS properties, when we define a CSS variable, we are also giving that variable a set scope. In CSS, the scope is what determines where a variable will work based on where it is declared. Variables can have two kinds of scope: local and global. So far we have only dealt with variables with local scope.
A locally scoped CSS variable will only affect the specific HTML element that it is declared in along with any children that element may contain.
<nav id="menu-items"> <ul> <li><a href='#'>One</a></li> <li><a href='#'>Two</a></li> <li><a href='#'>Three</a></li> </ul> </nav>
For instance, in the above code snippet, the <nav>
element with the id of 'menu-items'
contains an unordered list.
#menu-items { --menu-color-blue: blue; } #menu-items a { color: var(--menu-color-blue); }
Because the --menu-color-blue
variable was declared inside the #menu-items
selector, only #menu-items
and its children can reference the variable.
Globally scoped variables are declared in the :root
pseudo-class. This pseudo-class points to the root element of the document, hence its name. In most cases that root element is actually the <html>
element. By declaring variables in :root
they can be applied globally across the entire HTML document.
If we were to modify the previous example to instead declare --menu-color-blue
inside of :root
, then that variable would be able to be referenced anywhere in the document.
:root { --menu-color-blue: blue; } #menu-items a { color: var(--menu-color-blue); }
It is common practice to define variables inside the :root
selector but not mandatory. There are plenty of good reasons for declaring variables with limited scope. For instance, if a large website is being designed then it could be a cleaner solution to create variables within relevant components instead of having all the variables pile up in :root
.
Instructions
We want to alternate background colors for each artist that has a new release. Right above the .container
selector ruleset add an empty :root
pseudo-class.
Inside the :root
pseudo-class create a variable called --group-one-background-color
that has a value of #a01c32
.
Still inside of the :root
pseudo-class create a variable called --group-two-background-color
that has a value of #8A978A
.
Set the --group-one-background-color
variable as the value of the background
property for the .artist
selector ruleset and set --group-two-background-color
as the background
property for .artist:nth-child(even)
.
Inside the .btn
selector, create a variable called --button-hover-color
and set its value to be #7271D8
.
Finally, inside of the .btn:hover, .btn:focus
selector ruleset create a background
property and set its value to be --button-hover-color
.
Note that if you try to use this variable outside of the .btn
selector ruleset, nothing will happen!