csssass

Difference between SCSS variables and CSS variables?


I don't understand the difference between CSS custom properties (variables) and SCSS variables (I am new to Sass by the way).

If this CSS code:

:root {
    --someColor: coral;
}
  
body {
    background: var(--someColor);
}

achieves the same results as this SCSS code:

$someColor: coral;
    
body {
    background: $someColor;
}

Why were SCSS variables introduced? Are they really the same as CSS variables, or am I missing something?


Solution

  • SCSS is a preprocessor. That means it is not CSS, but is converted into CSS at 'compile time'. In the resulting CSS code there is no resemblance to the original SCSS code. Hence you cannot change the variable values at CSS 'runtime'.

    Historically SCSS is a fairly old technique. Actually it dates back to as far as 2007. It was invented by the motivation that CSS lacks certain features amongst which are variables (and nesting and loops and mixins etc.).

    CSS variables are a quite recent addition to the CSS standard (The last call working draft seams to be from 2014). They didn't render SCSS variables useless, because you can do things to SCSS variables which you can't do with CSS variables (to my knowledge) like color calculations.

    On the other hand you can do things with CSS variables that you can't do with SCSS variables like changing at runtime.

    BTW: CSS variables are not the official jargon. They should be called custom properties. But everyone calls them variables.

    Addendum 1

    One difference I was not talking about. You can't change SCSS variables with JavaScript. CSS Custom Properties however can be accessed and changed with JS

    Addendum 2

    This article on CSS Tricks has a good overview: https://css-tricks.com/difference-between-types-of-css-variables/

    Addendum 3

    As pointed out setting custom properties in CSS is the prefered way for reasons of freedom for later manipulation. However media queries can not handle custom propertien. So for media queries for instance things like breakpoints and the like SCCS or Sass variables are still (2024) the way to go.