What SASS Variables can do vs. What CSS native Variables can do
SASS variables give us a lot of flexibility and repeatability and were the first on the scene to begin to give front-end developers a modern syntax for keeping our code more DRY. Now that CSS Variables are on the scene — also referred to as CSS Custom Properties — we have new powers with this native implementation.
Both of them define variables in the global scope:
We can also define variables in a local scope:
But there is an important difference here. In SASS, you can redefine a variable inside another declaration, but it will only maintain that value until the declaration is closed. The global value will be applied again after that:
With CSS variables we can scope “element-relative” values, but here, the same variable will maintain that value whenever it is inside that element. This means that the variable can mean different things based on its context:
Further, CSS Variables cascade
Its a little bit of a mind-bender, but this starts to make sense if you already understand the “Cascade” in Cascading Style Sheets.
Math with Variables
Math can be done with the
calc() css function. With CSS variables, the output is messier because SASS renders the value of the math and removes it from the source code. For CSS Variables, on the source code, a reader will still see the math.
By Their Powers Combined
One can put these ideas together, though, and create a viewport-size-dependent set of font-sizes with much less code to achieve “Fluid Typography”.
Element scoping and CSS calc() together
The way the CSS works above is like magic — after a lengthy set of
:root declarations, the one line that follows basically sets the same calculations on three different elements and will result in three different sets of measurements within the one declaration.
Other reasons to use CSS variables:
- They can be changed via JS: CSS variables make dynamic themeing pretty easy. Have JS change the value of a few CSS variables and you have a user-generated theme.
- They support fallback values: The syntax of an inline fallback is
var(--custom-variable, fallback)as in
color: var(--text-color__default, #444);. It is not used to support old browsers, but rather it provides a fallback value in case the original value has not been defined.
Reasons not to use them quite yet:
- No support in IE 11 or Edge < 15: A fallback solution almost renders CSS variables useless. It means you have to declare a normal value as the fallback, i.e.
background-color: red; background-color: var(--bg-color).
:rootdeclaration is a way to declare values for CSS Variables that are global in scope. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”. ↩