31

With Sass' ability to use variables, one would hope there is a large set of logic functions we can do with them.

Is there a way to do something like this?

$someVar: someValue !default;

@switch $someVar
{
    @case 'red':
        .arbitrary-css here {}

    @break;

    @case 'green':
        .arbitrary-css here {}

    @break;

    @case 'blue':
        .arbitrary-css here {}

    @break;
}

However, I can't find anything in the Sass reference about this.

Bryce
  • 6,440
  • 8
  • 40
  • 64

2 Answers2

59

No there isn't any supported switch statement in sass but if you only need to use the switch statement to tweak a variable, you can use sass maps in a switch statement sort of way.

Using SASS maps in place of a switch statement

$newVar: map-get((
    case_1_test_name : case_1_return_value,
    case_2_test_name : case_2_return_value,
), $testVar);

So here's an example:

$vehicle: car;

$vehicleSeating: map-get((
    car : 4,
    bus : 20,
), $vehicle);

//$vehicleSeating = 4

The above example translated into if/else statements:

$vehicle: car;

@if ($vehicle == 'car') {
    $vehicleSeating: 4;
} @else if ($vehicle == 'bus'){
    $vehicleSeating: 20;
}

//$vehicleSeating = 4
Daniel Tonon
  • 9,261
  • 5
  • 61
  • 64
  • 19
    I'm providing an alternative to using switch statements in SASS by using SASS maps in a way that a lot of people wouldn't think of. I've removed the unrelated bit of the answer about generating CSS from a SASS map. – Daniel Tonon Oct 21 '15 at 04:46
  • So rather than the answer just being "it's not possible", the answer is "It's not possible, but you can try this instead" – Daniel Tonon Oct 21 '15 at 04:49
  • 4
    Just providing an alternative that is far cleaner than a stack of if/else statements. – Daniel Tonon Oct 22 '15 at 05:37
  • I think this is nifty technique. I'm even going to refactor some of mixins using sass maps for media queries. Thanks! – Vladyn Jan 24 '17 at 08:55
  • 1
    @Vladyn Try this mixin out for media queries. https://www.npmjs.com/package/mq-scss I think it's the most powerful media query mixin on the internet. – Daniel Tonon Nov 16 '17 at 04:47
  • Thanks @DanielTonon, this looks interesting. Very similar to one I'm using across latest 2 projects also as a SASS mixin – Vladyn Nov 16 '17 at 10:32
31

Sass doesn't support Switch Case.

Sass only support four control directives:

  • @if

  • @for

  • @each

  • @while