Demo
Summary
:root {
--main-color: red;
}
h1 {
background-color: var(--main-color);
}
p {
color: var(--main-color);
}
Details
Custom properties allow you to easily reuse values across a CSS file. For example, let’s say you have a color value that you are reusing on your site over and over again. Instead of copying and pasting it repeatedly, you can store it in a custom property and copy and paste the custom property name. The benefit here is if you need to update the color value, you only have to change it in one spot in your file instead of having to update it in multiple spots.
Custom properties are typically declared on the :root
pseudo-class, like in the example above. Custom property names must start with two dashes.
When using the custom property as a value in your CSS, use the var()
function.
Exercises
First, recreate the CSS code in the embedded CodePen demo. Then try customizing the value in the variable.