What are CSS variables and their differences with CSS Preprocessors

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:

(@azad6026) on CodePen.

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.

You could also manipulate them through Javascript. Also CSS variables are available through DOM so you can change them according to media query changes. It means you can change a property value based on your device width.

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
  • They have access to DOM so they an be manipulated through JavaScript
  • 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.

Read up about CSS variables in this article an watch the videos at the end of this css tricks article.



© 2020
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.