Saiyam Gambhir Saiyam Gambhir - 2 months ago 15
Sass (Sass) Question

Scss variable benefits?

Hi i am doing scss for the first time and have some doubts.

Consider i make a variable

$multipler : 10px;
and use it for all the properties where i have to give the value in px.

Then if i want font size to be 20px somewhere i will use

.foo { font-size : $multiplier * 2 } // 20px


So my question is whats the difference in using

.foo { font-size : $multiplier * 2 } // 20px


OR

.foo { font-size : 20px } // 20px


Both gives 20px so which one is better ?

Answer
.foo { font-size : 20px } // 20px

That is, quite simply, what it is. If you use 20px in several places in your code then you will have to change it manually, if you want the value to change.

If you use a variable, like:

$multiplier: 10px;

Then you can change that value in one place in your code. For example, if you have code like this:

$multiplier: 10px;
body { padding:$multiplier } /* 10px */
#header { padding:$multiplier } /* 10px */
#content { padding:($multiplier * 2) } /* 10px x 2 = 20px */
#sidebar { padding:$multiplier } /* 10px */

Then you can just change the $multiplier value once, and it will change everywhere. The multiplication by 2 will also change accordingly:

$multiplier: 20px;
body { padding:$multiplier } /* 20px */
#header { padding:$multiplier } /* 20px */
#content { padding:($multiplier * 2) } /* 20px x 2 = 40px */
#sidebar { padding:$multiplier } /* 20px */

If you use something like this:

.foo { font-size : 20px } // 20px

Then you have to change the value by hand (or search and replace it). There is nothing wrong with doing it like this, but if you are using LESS/SCSS then you are doing yourself a disservice not using variables. If used carefully they can be very powerful. Just keep in mind that when changed your entire website will change as well, so be careful how you use them (you may end up changing stuff that should not be changed).

Comments