2

I have widths of different planets

$mercury-width: 20px;

$venus-width: 30px;

$earth-width: 20px;

and their names:

`
$planets: mercury, venus, earth;
@each $planet in $planets {
      .#{$planet} {
        width: #{$planet}-width;
      }
    }

it doesn't work.

expected result:

.mercury {
    width: 20px;
}

etc.

How can I do that?

fleple
  • 95
  • 8

1 Answers1

3

How about this:

$planets-width: (mercury: 20px, venus: 30px, earth: 20px);
@each $name, $width in $planets-width {
      .#{$name} {
        width: $width;
      }
}

Result:

/* line 3, ../scss/test.scss */
.mercury {
  width: 20px;
}

/* line 3, ../scss/test.scss */
.venus {
  width: 30px;
}

/* line 3, ../scss/test.scss */
.earth {
  width: 20px;
}

If you want both color and size you can use nested maps:

$planets-map: (mercury: (width : 20px, color: red), venus: (width : 30px, color : purple), earth:( width: 20px, color: blue));
@each $name, $properties in $planets-map {
      .#{$name} {
        width: map-get($properties, width);
        color: map-get($properties, color);
      }
}

Result:

/* line 3, ../scss/test.scss */
.mercury {
  width: 20px;
  color: red;
}

/* line 3, ../scss/test.scss */
.venus {
  width: 30px;
  color: purple;
}

/* line 3, ../scss/test.scss */
.earth {
  width: 20px;
  color: blue;
}
JAre
  • 4,666
  • 3
  • 27
  • 45
  • Thank You, but if i have a loop of colors of planets, should i make another array, for example $planets-color: (mercury: red,earth: blue); and after that another @each. it's too more – fleple May 07 '14 at 18:47
  • @JangBi it was fun to write. Btw you can accept answer ;) – JAre May 08 '14 at 14:39