hyde
hyde

Reputation: 2585

Use string as vairable in SASS

I have variables $person-color and $animal-color in a separate variables.scss file which I want to use in my main.scss file.

What I want to achieve is the following CSS:

.person-container {
    background: blue;
}

.animal-container {
    background: red;
}

My SCSS looks like below:

$items: person animal;

@each $item in $items {
  .$item-container {
      background: #{$item}-color;
  }
}

This won't work. But I want to expand the value of the variable in the string #{$item}-color. Is there a way to get the output above without using a map?

Upvotes: 0

Views: 61

Answers (1)

Stubbies
Stubbies

Reputation: 3114

Partials need to start with an underscore ex. _variables.scss or else it will compile into a .css

_variables.scss

$person: red;
$animal: blue;

main.scss

@import 'variables';

$items: person $person, animal $animal;

@each $item in $items {
  $key: nth($item, 1);
  $value: nth($item, 2);

  .#{$key}-container {
      background: $value;
  }
}

Edit: Now should give you the right results!

Upvotes: 2

Related Questions