Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Custom properties/CSS variables – CSS

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.

References

Using CSS custom properties (variables) on MDN

Back to: CSS Reference > Intermediate CSS