10

I'm in the process of converting a stylesheet from LESS to SCSS and I'm confused about something I'm seeing with variable scope. Reproduced with a simple example:

$my-color: #000;

#logo {
    $my-color: #555;
    color: $my-color;
}

a {
    color: $my-color;
}

Converts to the following CSS:

#logo {
    color: #555555;
}

a {
    color: #555555;
}

The equivalent construction in LESS would result in the a color value being #000 as the variable declaration within the #logo scope would override the more general one but only within that scope. Do variable scopes not work like that in SCSS? Is there a way to achieve the same thing?

cimmanon
  • 67,211
  • 17
  • 165
  • 171
Rob Fletcher
  • 8,317
  • 4
  • 31
  • 40

2 Answers2

26

This is no longer the case at least as of SCSS v3.4.12:

Now it scopes correctly the variables:

Input:

$my-color: #000;

#logo {
    $my-color: #555;
    color: $my-color;
}

a {
    color: $my-color;
}

Output:

#logo {
  color: #555;
}

a {
  color: #000;
}

Can be tried out in: http://sassmeister.com/

justinsAccount
  • 742
  • 1
  • 10
  • 10
10

Reading through the answers to Sass variable default scope it seems that variables work differently in SCSS to LESS.

In this case the definition of $my-color in #logo changes the value of the global variable whereas in LESS it would be treated as a block local override of that global variable.

I guess I'll have to structure things a little differently in order to achieve the same result.

Community
  • 1
  • 1
Rob Fletcher
  • 8,317
  • 4
  • 31
  • 40
  • 5
    In my opinion this is bad, because you are polluting global space. You have to think up a new variable name every time you're entering to the new block, this leads to variable names: `$color`, `$color1`, `$color2` .... – Jakub Truneček Nov 21 '13 at 14:49
  • 2
    Pretty soon Sass will have proper lexical scoping, and you'll be able to override global variables like this: `$var: newvalue !global;` -- Sass 3.3 already gives a deprecation warning when you override a global without `!global`. – Paul d'Aoust May 15 '14 at 17:56
  • 2
    Warning: This is no longer the case. See answer below. – justinsAccount May 10 '15 at 23:19