Home > Back-end >  Is it possible to reassign or increment/decrement a variable in SASS?
Is it possible to reassign or increment/decrement a variable in SASS?

Time:11-14

I have setup a style-rule using SASS to animate some elements in my application.

It was originally setup like this (where $dropdown-length is 1.5s):

    &:nth-child(2) {
      animation-delay: ($dropdown-length   0.2s);
    }

    &:nth-child(3) {
      animation-delay: ($dropdown-length   0.4s);
    }

    &:nth-child(4) {
      animation-delay: ($dropdown-length   0.6s);
    }

    &:nth-child(5) {
      animation-delay: ($dropdown-length   0.8s);
    }

    &:nth-child(6) {
      animation-delay: ($dropdown-length   1s);
    }

    &:nth-child(7) {
      animation-delay: ($dropdown-length   1.2s);
    }

    &:nth-child(8) {
      animation-delay: ($dropdown-length   1.4s);
    }

    &:nth-child(9) {
      animation-delay: ($dropdown-length   1.6s);
    }

As you can see, this is very repetitive and not very DRY. So I attempted to use the benefits of SASS. I came up with:

    @for $num from 2 through 10 {
      $i: 0;
      &:nth-child(#{$num}) {
        $i: $i   0.2s;
        animation-delay: ($dropdown-length   $i);
      }
    }

However, I am struggling to find if it is possible to increment another variable (in this example $i) on each iteration in the for loop. At the moment, it seems to just set $i to 0.2s and stays constant at 0.2s for each iteration. I would like for $i to increment by 0.2s for each successive iteration. Any ideas? Thanks.

CodePudding user response:

As @Justinas says, your loop resets itself every iteration. You should take $i out of the loop, something like this:

$dropdown-length: 1.5s;

.foo {
    $i: 0;
    @for $num from 2 through 10 {
        &:nth-child(#{$num}) {
            $i: $i   0.2s;
            animation-delay: ($dropdown-length   $i);
        }
    }
}

Which outputs:

.foo:nth-child(2) {
     animation-delay: 1.7s;
}
 .foo:nth-child(3) {
     animation-delay: 1.9s;
}
 .foo:nth-child(4) {
     animation-delay: 2.1s;
}
 .foo:nth-child(5) {
     animation-delay: 2.3s;
}
 .foo:nth-child(6) {
     animation-delay: 2.5s;
}
 .foo:nth-child(7) {
     animation-delay: 2.7s;
}
 .foo:nth-child(8) {
     animation-delay: 2.9s;
}
 .foo:nth-child(9) {
     animation-delay: 3.1s;
}
 .foo:nth-child(10) {
     animation-delay: 3.3s;
}
  • Related