Search code examples
csssasscompass-sass

Mix two SASS variables inside a loop


I have few scss variables which looks like :

$box-bg1: #7a8360;
$box-bg2: #918261;
$box-bg3: #6a8177;
$box-bg4: #686f5e;

I want to use these variables inside a for, like :

@for $i from 1 through 4 {
  .locationBox:nth-child(#{$i}) { background: $box-bg#{$i}; }
}

After compiling code i get this error : Syntax error: Undefined variable: "$box-bg", which looks like the #{$i} variable does not make any sense for my code. Is there a way to use a variable inside a loop like this?

Note : I also use compass


Solution

  • Sass does not support variable variables. To programatically create your selectors, you would have to do it using lists:

    $box-bg: #7a8360, #918261, #6a8177, #686f5e;
    
    @for $i from 1 through length($box-bg) {
      .locationBox:nth-child(#{$i}) { background: nth($box-bg, $i); }
    }
    

    Output:

    .locationBox:nth-child(1) {
      background: #7a8360;
    }
    
    .locationBox:nth-child(2) {
      background: #918261;
    }
    
    .locationBox:nth-child(3) {
      background: #6a8177;
    }
    
    .locationBox:nth-child(4) {
      background: #686f5e;
    }