How to Use Variables in CSS

How to Use Variables in CSS

Ferenc Almasi β€’ 2020 November 23 β€’ πŸ“– 2 min read

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:

/* 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
Copied to clipboard!

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.

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
Copied to clipboard!

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
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript
10 Best Practices for Quickly Improving Your CSS

Resources:

JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended