A Friendly Introduction to CSS Variables
We’ve used preprocessors like Sass and Less to handle dynamic values and variables, and they’ve helped keep our CSS code organized and much easier to maintain.
These preprocessors has also helped us minimize repetition of code and also increased productivity.
However, dynamic features are growing increasingly in CSS, and now we can use variables natively in CSS. In this article you’re going learn what are CSS properties and also how to use them.
What are CSS variables?
You’ve probably heard the word variable or even used them, that’s if you’re familiar with any programming language. They basically let’s you store values.
What I illustrated above is quite straight forward, I stored my age in a variable called myAge and I did the same with my height, then I did a console.log(). which will output 23 and 175.5. Basically, this is how CSS custom properties works. They let you store value so they can be called and used over and over again. Cool right?
Declaring a variable
Using the variable
In most cases you’ll see the properties declared inside the root, like this
Variables defined in the :root are global variables, which means they would be available every where, but there is also a way to limit a variable, they are called scoped variables. We’ll talk more on it towards the end of this article.
Using them is quite straight forward
Such a weird syntax! don’t worry you’ll get use to it :)
What are scoped variables? Basically, they are variable that only applies to the element that they were assigned for. Which means they wouldn’t work outside that scoped element. A basic example
Apply the values to the box class
The styles doesn’t only apply to the .box class but every thing inside of it.
Let say you have a variable called –box-color with a value of #2dc997 scoped to the .box class in your CSS.
Browser Support for CSS Variables
It wouldn’t come as a shock that IE11 has no support for CSS variables, but all other major browsers have full support for it.
But we still have a way to make it work for non-supporting browsers, if we want. Let’s help those 4 people that still uses IE
Now the question remains, do we still have need for preprocessors? Yes we do, While CSS(3) is becoming a more dynamic syling language, with the introduction of grid, advanced selector, webfonts etc and CSS custom properties being one of its cool features, there are still limitations.
With preprocessors like Sass and Less we have tons of features, things that we would not be able to do with just pure CSS. I’m talking about fetures like prefixing parent selector references, variable expansion in selectors, control directives, list data type, defining custom functions, keyword arguments etc. So yes we still need them, atleast for now.