DEV Community

Cover image for CSS variables: What are they and how to use them
John Palmgren
John Palmgren

Posted on

CSS variables: What are they and how to use them

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

Top comments (2)

Collapse
 
prakhart111 profile image
Prakhar Tandon

Hey John,
Want to add a few points on CSS variables.

  • It is recommended to add a fallback condition in case of inability to access the variable, CSS will use that fallback item.
.myClass {
  background-color: var(--bg-color , black)
  color: var(--text-color , white)
}
Enter fullscreen mode Exit fullscreen mode

The values after the comma, represent fallback values.

  • CSS variables are inherited and are also available in any of that selector's decedent.

A variable declared in :root , means it's in the root element ( think it as html tag )
Hence it is accessible globally.

And yes, on dev, to get such colourful code, just use "js" after first commas

Cheers !

Collapse
 
johnpalmgren profile image
John Palmgren

Thanks for your comment. Some great points ❤