CSS variables: What are they and how to use them

John Palmgren - Jan 26 '22 - - Dev Community

What are they

CSS custom properties aka CSS variables allow you to define a property in a variable that you can use over and over again. There are a number of use cases for this: often you will use the same colors for a brand or a particular theme. The big benefit of using variables for commonly used properties is that if you need to change it further down the line you can simply change the variable. This will save you from having to find everywhere in your code that you used that property.

How to use them

Apply the variable to an element

You first need to declare what element it should be applied to. You can apply it to any element but it is common to apply it to the root element so it can be used anywhere in your CSS (global scope). Use the :element {} syntax to select the element. You can choose any name for your variables but they are case sensitive.

:root {
  --bg-color: #4B6CDB;
  --text-color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

Calling the variable

You can call the variable by using var(). Instead of putting in the property name call the variable name inside the var function

.myClass {
  background-color: var(--bg-color)
  color: var(--text-color)
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . .