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);
}
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);
}
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.
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: