Writing a loop that increments by a value other than 1 in Sass

后端 未结 4 694
有刺的猬
有刺的猬 2020-12-05 23:09

In SASS, a loop is written like so:

@for $i from 1 through 100 {
    //stuff
}

This would yield 1, 2, 3, 4... all the way to 100.

H

相关标签:
4条回答
  • 2020-12-05 23:17

    Other example more:

    .my-class {
        $step    : 5;
        $from    : ceil( 1 /$step);
        $through : ceil( 100 /$step);
        $unit    : '%';
    
        @for $i from $from through $through {
          $i : $i * $step;
          width: $i#{$unit};
        }
    }
    
    0 讨论(0)
  • 2020-12-05 23:30

    I'd use Modulus for this. The Modulus operator gives you the remainder of the division of a number into another number. E.g (3 % 2) will give you 1, as will (5 % 2) or (7 % 2).

    If you used this:

    @for $i from 1 through 100 {
        @if $i % 2 == 0 {
            #{$i}
        }
    }
    

    You'll get 2,4,6,8,10...100

    But you want 1,3,5,7,9...99 – so offset it by 1:

    @for $i from 1 through 100 {
        @if ($i+1) % 2 == 0 {
            .your-class-#{$i} {
              // do stuff
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 23:39

    Sass does not provide a way to specify how much to increment using @for loops. Instead, you write your loop to reflect how many steps you need to take to get your final output. For all of the odd numbers from 1 through 100, that's 50 steps (100 / 2). Inside the loop, you use arithmetic (addition, subtraction, multiplication, division) to arrive at your final value.

    @for $i from 1 through 50 {
      $value: $i * 2 - 1;
      // stuff
    }
    

    DEMO

    or a bit more general version:

    $max: 100;
    $step: 2;
    
    @for $i from 1 through ceil($max/$step) {
      $value: ($i - 1)*$step + 1;
      // stuff
    }
    

    DEMO

    0 讨论(0)
  • 2020-12-05 23:43

    It isn't in the documentation because it simply isn't implemented. What you want to do can be done with the @while directive.

    $i: 1;
    @while $i < 100 {
      // do stuff
      $i: $i + 2;
    }
    
    0 讨论(0)
提交回复
热议问题