A lot of people don’t know about CSS variables, and you might be one of them! It’s time to learn about CSS variables and how you can use them.
CSS variables are declared for a specific element as a custom property. Then, you can use that custom property anywhere you use that element.
Declaration and Usage
Here’s how you declare a custom property:
element can be a selector of any element, for example, div, p, .test, etc…
What we did is that we declared a custom property for this element called
--background-color . All CSS custom properties must start with
Now, we can use this custom property inside
element using the
Here, we assigned the background-color property of
element to the variable we declared earlier.
This is nice and all, but usually we have repetition inside different elements, not just one. declaring a custom variable inside one element type is not very convenient.
In order to use a custom property inside more than one element type, we can declare the custom property inside the
Now, we can use the variable
--primary-color inside any element in our document:
By declaring our custom property inside
:root , we are now able to use it inside
div to set the text color,
p to set the background color, and any element having class
fancy to set the border color. This way, not only did we minimize repetition, but we also made it easier to edit and change our website’s primary color at any given point.
Elements can also inherit custom properties. For example, let’s say we have the following HTML:
Then, we declare a variable called
Now, we can use
--text-size not only inside
.parent , but also inside its children as well:
We can also override custom properties. We can do that by redeclaring the custom property inside the child element:
Now, if you use
.second-child , it’ll be evaluated to 30px, but if you use it inside
.parent, it will still be 15px.
You can also define a fallback value for a variable by passing a second parameter to
var . For example:
font-size: var(--text-size, 30px);
Fallback values are used when the variable is not defined yet. They are not used as a fallback to browser incompatibility.
And that’s how you can use CSS variables! Keep in mind that some browsers like Internet Explorer don’t support them, so if you need to support all browsers you need to take that into consideration.