Aerra
Aerra

Reputation: 84

Sass loop incrementing by 100

I want to write a for loop which increments with 100 each time ($i), and increments another variable by 50 each time ($j).

I tried to follow the examples in other questions about sass incremental loops, but I can't seem to be able to figure out how to apply to my case specifically.

$max: 2600;
$step: 100;
$j: 150;

@for $i from 1000 through $max {
  $i: $i + $step;
  $j: $j + 50;
  // stuff
  @media screen and (min-height: #{$i}px) {
    .item {
      transform:
              translateY(calc(-100% - #{$j}px));
    }
  }
}

this is the current CSS output:

@media screen and (min-height: 1100px) {
  .item {
    transform: translateY(calc(-100% - 200px)); } }

@media screen and (min-height: 1101px) {
  .item {
    transform: translateY(calc(-100% - 250px)); } }

@media screen and (min-height: 1102px) {
  .item {
    transform: translateY(calc(-100% - 300px)); } }

// ..etc

the desired CSS output:

@media screen and (min-height: 1000px) { // $i is 1000
    .item {
      transform:
              translateY(calc(-100% - 150px)); // $j is 150
    }
  }

@media screen and (min-height: 1100px) { // $i is 1100
    .item {
      transform:
              translateY(calc(-100% - 200px)); // $j is 200
    }
  }
@media screen and (min-height: 1200px) { // $i is 1200
    .item {
      transform:
              translateY(calc(-100% - 250px)); // $j is 250
    }
  }

...

// and so on and so forth until min-height is 2600

EDIT

This is the working code, thank you

$max: 26;
$step: 100;
$j: 100;

@for $i from 10 through $max {
  $k: $i * $step;
  $j: $j + 50;

  @media screen and (min-height: #{$k}px) {
    .item {
      transform:
              translateY(calc(-100% - #{$j}px));
    }
  }
}

Upvotes: 1

Views: 712

Answers (1)

Talha Akbar
Talha Akbar

Reputation: 10030

$max: 26;
$step: 100;
$j: 150;

@for $i from 1 through $max {   
    $k: $i * $step;
    $j: $j + 50;

    // Use $k and $j in the styles instead of $i

Instead of adding $step to $i, you need to multiply * it with the $step. Also, change the variable name from $i to something else since it will override the loop variable $i.

Edit: Just realized you will also need to change your start and end of the loop.

IMPROVED ANSWER: My old answer works but, I believe it works at the expense of readability. I would suggest you initialize $k with an initial value just like you did with $j and add $step to $k each time independent of $i in each iteration:

$max: 26;
$j: 150;
$k: 100;
$stepK: 100;
$stepJ: 50;

@for $i from 10 through $max {   
    $k: $k + $stepK;
    $j: $j + $stepJ;

// Use $k and $j in the styles instead of $i

Upvotes: 2

Related Questions