Personal blog of Asif Kabani. You can follow me on Twitter or get in touch with me through my website at asifkabani.com.
CSS variables give you the opportunity to declare variables in your CSS code. Currently, the support is around 96%, which means you should be able to use it without worrying. Of course to be at 100% confidence, you can always check Can I use to make sure that you are not trying to target a browser that is not capable.
Custom properties or CSS variables allow us to re-use a variable property to substitute inside of a CSS property. Let's take a look at an example.
:root {
--my-bg-color: blue;
}
.my-class {
font-size: 16px;
background-color: var(--my-bg-color);
}
.my-other-class {
font-size: 20px;
background-color: var(--my-bg-color);
}
In our example above, we are declaring a variable name under :root
psuedo-class. When we define our variable --my-bg-color
under this psuedo-class, we are able to use this anywhere globally in our code. We call the variable in our code using the var()
function provided. This injects the property value of --my-bg-color
inside our property value so the output would replace the statement with the color blue in this case.
The var()
function can accept a default or fallback value to the property value if our custom variable name is not defined or available.
.my-other-class {
font-size: 16px;
background-color: var(--my-bg-color-value, red);
}
In the scenario above, if the value of --my-bg-color-value
is not available, then the default value of red
will be called in this case and used. We can also add more variables to the check if needed.
.my-other-class {
font-size: 16px;
background-color: var(--my-bg-color, (--my-bg-color-value, red));
}
Here we are checking for two variables, and if neither are found then we default the value to be red
. Do note that doing this may cause performance issues as it takes more time to parse through the variables.
CSS variables are great to use in your CSS to declare custom values
We declare our variables inside the :root
psuedo-class
Using the var()
function we can call our custom property inside of a property
You can chain multiple calls as the second argument to var()
, but there may be performance implications