Just as CSS variables are subjected to local and global scope, they also follow standard CSS inheritance. If a variable is not explicitly defined on a child element, the value of its parent variable is used if there is one. This can be important to keep in mind as some property values set on parent elements are inherited by their child elements and some aren’t. As a reminder widths, margins, paddings, and borders do not inherit.
As we saw in the previous exercise, different scopes allow for the same variable to have multiple values when declared in multiple locations.
h1 { --color: pink; } p { --color: blue; } h1 { color: var(--color); } p { color: var(--color); }
Above, the --color
variable is being declared and referenced in both the <p>
and <h1>
selectors. But in each case the color value is different. CSS has no issues with using variables this way because both variables are locally scoped. We can think of it like the <h1>
selector only ever knowing about the --color
variable declaration with a referenced value of pink. With the same being true for the <p>
selector.
It is also possible to override a variable’s value. A common case for doing this is when we want variables to change only in a specific section of a webpage. For example, if we want a different shade of orange for button elements inside the navigation bar from a submit button elsewhere on the page.
We can re-declare an --orange-color
variable inside of a specific button selector. And when that --orange-color
variable is referenced in the specific selector it will be the locally chosen orange color.
:root { --orange-color: #FF933A; } body { background-color: var(--orange-color); } button { --orange-color: #BF6317; color: var(--orange-color); border: 1px solid black; }
Instructions
Declare a variable named --sub-title-text-size
in the .section-title
selector ruleset. Set the variable’s value to be 2.5rem
.
Using the var()
function, set the --sub-title-text-size
variable as the value of the font-size
property in .section-title
.
Declare another variable with the name --sub-title-text-size
in the .artist-title
selector ruleset and set its value to be 1.8rem
.
Again, set the --sub-title-text-size
variable as the value of the font-size
property in .artist-title
. Notice how the font sizes for both sections are different even though both variables have the same name.
Redeclare the --main-header-color
variable, which was moved to the :root
pseudo-class, in the .footer-container
selector ruleset. Give the variable a value of #7D6B91
. Then set --main-header-color
as the value of the background
property.
Notice how the header’s font color stayed the same but the footer now has a new color even though they are both using the main-header-color
variable.