DEV Community

Cover image for CSS Variables: Quick guide
Clément Creusat
Clément Creusat

Posted on • Edited on

CSS Variables: Quick guide

Even though CSS Variables aka Custom Properties have been more than usable for 3-4 years now, not everyone knows about them or uses them.

They are a great addition to CSS. One of the best since CSS 3. A lot of new features are coming and are announcing a great time for CSS again!

I will write a short series about them and we will go deeper into their use.


How do they work?

Declaration of CSS Variables

Looking at this picture, you will notice 3 things:

Top level / Root level

CSS Variables are declared at root level. It's not an obligation and we are going to explore it but it became the standard approach.

:root {
 --main-bg-color: grey;
 --font-family: 'Overpass', sans-serif;
 --font-medium: 16px;
}
Enter fullscreen mode Exit fullscreen mode

How to declare and use them

We declare them with double hyphen -- and a name as we would do in a SASS variable :
--main-bg-color vs $main-bg-color

You add a value to them. Could be font-family, font-size, spacings, url images, ...

--name: value;
Enter fullscreen mode Exit fullscreen mode

The use of the var() function

To read them, we will use the var() function and add two things:

  • The first one is the variable itself
var(--main-bg-color)
Enter fullscreen mode Exit fullscreen mode
  • The second one is a default value if the variable is not defined:
var(--main-bg-color, lightgrey)
Enter fullscreen mode Exit fullscreen mode

If --main-bg-color doesn't exist, the color by default will be lightgrey


What are the benefits of using them?

✅ They are easy to write, to use and to maintain. They are reusable in all your CSS files. Super useful when working with components and shared properties/values.

🚀 They can be changed at local scope. I will cover it in the next article, be there!

⚙️ They are accessible at runtime. You can change one variable in your browser to see how it affects your design. Impossible with build time preprocessors. And are accessible by JavaScript: we can create them with JavaScript, use them or change them.

🔲 🔳 When working with dark/light mode or multiple themes in CSS, they are perfect. I will add an example and comparing with the use of SASS variables. Be there too 😉

Top comments (0)