In this post we learn about CSS variables and their differences with CSS Preprocessors. As we know the variables have been introduces some time ago and they solve the very problem of using variables in CSS for reusable properties. Lets have a look at this example:
You simply define the variable in root and use it wherever you want to. It is pure CSS. It does not need to be complied as in CSS Preprocessors like SASS or LESS or Styles , etc. Lets see the equivalent code in SCSS:
This SCSS code has the exact similar result as the previous example.
We will have a look at another example that shows cascading of variables in CSS variables which demonstrates their cascading ability throughout the code.
The body H2 will have orange colour which means the children could have different colours using CSS variables.
Lets see the differences in terms of tech sight.
Why use CSS Variables
- They are native CSS and browsers understand them but Preprocessors need to be compiled before serving to browser
- They cascade. You could set up a new variable inside any selector to override its current value
- Their values could be changed with media queries and browsers respond accordingly
Why use Preprocessors
The browser support. With them you don’t need to worry about it as they will be compiled to pure CSS.
Should we us CSS variables
Absolutely. They are ready to be used. There are lots of other things that you need to read here and here to learn more about CSS variable. Browser support. In desktop only internet explorer does not support it. IE phone and opera mobile do not support it in mobiles. So good support so far.