In this post
Context
In the frontend world, it’s common to talk about CSS preprocessors to get some extra tools and features that are not available with regular CSS. While there are several preprocessor options, according to recent GitHub statistics Sass is the most popular.
As a preprocessor, Sass has many features beyond the ability to use variables like in a programming language. But, the goal of this article is to specifically compare Sass variables with regular CSS variables. Is there any difference at all? Is one better than the other? Or at least, is there a technical difference between these two options?
The real difference
Even though Sass is more flexible in some things than regular CSS, there is something that needs to be pointed out about the use of variables: For the DOM and the CSSOM, the CSS custom properties exist, but Sass variables don’t.
That means it is possible to change the value of a CSS custom property with JavaScript and that is going to affect every single property using that value. But with Sass variables, this is not possible at all because the Sass variables are compiled into plain values for CSS properties where they were placed.
The final product with Sass is not going to include any reference to the variables. In the example, $mainColor is not available on the CSS after the compilation. Sass variables are not converted into CSS custom properties, they are just converted into the value of the property where it was placed. As a result, to update the value of these properties it would be necessary to use JavaScript to add an extra class with the new values, or directly override the value of that element, which might not be ideal for maintainability.
Agnostic approach
Using Sass is not an impediment to using CSS custom properties. The compiled process of Sass won’t mess around with the CSS native functionalities like the custom properties. So, it is possible to use Sass with CSS custom properties. In fact, this would be the recommended route to follow since it would allow a smooth JavaScript-CSS interaction.
The only downside to this approach is it does not work with discontinued or outdated browser versions that don’t support CSS custom properties.
Final thoughts
A CSS preprocessor will give you more tools to work with than plain CSS. This is a fact, but to revisit the questions asked at the beginning of this article, it is safe to say that: Style-wise, both options are the same. The technical difference is that CSS custom properties will be visible for the DOM, Sass variables stop existing after the compiling process.
Therefore, if you plan to manipulate your styles with JavaScript which is very common in instances such as applying a light/dark switch option, you should try using CSS custom properties. It has worked out very well for us.
Interested in working with us? Have a look at our careers page and reach out to us if you would like to be a part of our team!
Top comments (0)