gskalinskii
gskalinskii

Reputation: 965

SASS - Can I define variable within for loop?

$x: 100%;
@for $i from 1 through 5 {
  .item-#{$i} {
    width: $x;
    $x: $x - 10;
  }
}

Can I define $x as 100% so it won't be global(if I may say so) and do calculations with it within the loop? Pass it as an argument maybe? Or it must be a function?

Upvotes: 1

Views: 2721

Answers (1)

Martin Turjak
Martin Turjak

Reputation: 21214

You can entirely base it on the $i variable and calculate it on each step (without using recursion). Something like this maybe:

@for $i from 1 through 5 {
  $x: 110% - $i * 10;
  .item-#{$i} {
    width: $x;
  }
}

DEMO

but then (if your real case is not much more complicated than this example) you also don't really need a separate variable and just do:

@for $i from 1 through 5 {
  .item-#{$i} {
    width: 110% - $i * 10;
  }
}

This way you overwrite your $x on each step of the iteration. But alternatively you can use Sass' if() function and do something like this:

@for $i from 1 through 5 {
  $x: if($i < 2, 100%, $x - 10);
  .item-#{$i} {
    width: $x;
  }
}

DEMO

where on the first iteration step you define $x and assign its initial value ... then you can modify $x in each step of the loop and pass it to the next.

In both cases $x is only defined in the scope of the @for directive and you can not access it form the outside (hence it is a local variable). But bear in mind that any global variable with the same name will get overwritten.

Upvotes: 2

Related Questions