One of the first reasons people turn to Sass is the existence of CSS variables.
Have you ever had to search and replace many occurrences of the same CSS value? If so, variables will help you out.
You need to prepend a variable with a
$ dollar sign:
This line doesn’t do anything apart from defining a variable, in our case a shade of yellow:
We can then use it throughout our CSS, whenever a color unit is required:
.scss file will be compiled into a
.css file, where all variables will be replaced with their actual value:
Why is it called a variable?
Well here, the value
#fce473 is variable. Meaning the name
$yellow remains fixed but the value can change.
Set your variable only once
To illustrate the purpose of using variables, you need to use it more than once, like this pink shade:
This will be compiled into:
If you decided to go for a different shade of pink:
You’d only have to change the color value once:
And the resulting CSS would be automatically updated:
Even more abstraction
Now let’s say you actually don’t want to use pink as your primary color, but green!
You’d have to define a
$green: #32cd32; variable and replace all the instances of
$green in your SCSS.
There is a better way:
Instead of directly referencing the variable
$green, you define a primary color variable that is set to
When you think about it, you don’t really want to use
$green throughout your CSS. What you actually want is use your primary color, which happens to be green.
If you decided to use
$blue as your primary color, you’d only have to modify a single line.
For any type of value
We’ve used variables to define colors, but you can set any type of content: