πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Use Variables in CSS

How to Use Variables in CSS

Ferenc Almasi β€’ 2020 November 23 β€’ Read time 2 min read
  • twitter
  • facebook
CSS

CSS variables have been a feature that CSS lacks for a long time. CSS preprocessors filled this deficiency and provided an easy way to use them. However, now you can also define and use variables right inside CSS without any preprocessor:

Copied to clipboard! Playground
/* Create variables on the root and access them with the var(); function */
:root {
    --main-bg-color: aliceblue;
}

body {
    background-color: var(--main-bg-color, #FFF);
}
css-variables.css

You can declare new variables by using a double hyphen followed by an arbitrary name. You can use any valid CSS property as a property value. The ruleset where you define a variable will define its scope where it can be used.

Copied to clipboard! Playground
span {
    --main-bg-color: aliceblue;
    background-color: var(--main-bg-color, #FFF);
}

/* Note that you can't use `--main-bg-color` here as it has been defined inside the span */
div {
    background-color: var(--main-bg-color, #FFF);
}
css-variables.css

If you want to use variables globally, you can add your variables for the :root pseudo-class, therefore it will be available for all rulesets.

Also note, that you can define fallback values as a second parameter passed to the var function. This value will be used if the variable cannot be found.

Note that fallback values won't fix compatibility issues. If the browser doesn't support CSS custom property, var will be an invalid value.

At the writing of this, it has a ~96% global support, where IE is unsupported. For the full list of support table, you can refer to caniuse.com.

How to use variables in CSS
If you would like to see more Webtips, follow @flowforfrank

10 Best Practices for Quickly Improving Your CSS

Resources:

  • twitter
  • facebook
CSS
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.