How to Use Variables in 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:

/* 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

10 Best Practices for Quickly Improving Your CSS

Resources:

Remove ads
Remove ads

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
🎉 Thank you for subscribing to our newsletter. x 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.