Learn how to define and use a CSS custom property (also called CSS variable). We'll look at the difference between global and scoped custom properties. And we'll see how using local variables for element states - in this case,
a:hover - allows extending default CSS capabilities by enabling overriding the
:hover color via an inline style.
Stephanie Eckles: [0:00] Here, we have a headline and a link, which currently are inheriting their colors from the default browser styles. We're going to use CSS custom properties, also called CSS variables, to update their colors.
[0:12] First, we'd like to create a color property that will be intended to be shared across multiple elements. The convention for this is to attach the styles to the root. The format for creating a CSS custom variable is two dashes followed by the name of your custom variable, and then any valid CSS values.
[0:32] For my color, I'm going to choose rebeccapurple. To apply this, I'm going to select my h1 and for the color property, to access that variable, we use the var function. Here, we pass in the name of our custom property. You can see that that has been updated to my rebeccapurple color.
[0:50] For my link, we could use the same thing, but another feature of custom variables is that we can scope them to specific elements. We can create a scoped variable of simply color. We will set its initial value to our variable of color primary, which we access in the same way as if we were using it on a property. Then, we'll update the links property to use that local variable. On save, I have the same results.
[1:40] Instead, let's jump back up to our main link element and define a local variable of hoverColor that we'll set to our green. Then, within our hoverRule, we will redefine the color using that hoverColor value. So far, we get the same result.
[1:55] Now, we can jump back into our HTML and we have the ability to style just the hoverColor, something that we traditionally can't do with an inline style because we've created a variable to redefine it. An inline style is going to have higher specificity in the cascade, which means redefining this property on an inline style is going to take priority over the rule in the style sheet.