student42
student42

Reputation: 171

Making @for loop with iteration in sass

Im trying to make a loop with sass iteration. This is my scss code:

@for $i from 1 through 4{
  &:nthchild(#{$i}){
    animation: xfade 24s 24s - $i * 6 infinite;
  }
}

And this is my output:

#slideshow:nthchild($i) {
  -webkit-animation: xfade 24s 23s infinite;
  animation: xfade 24s 23s infinite;
}

#slideshow:nthchild($i) {
  -webkit-animation: xfade 24s 22s infinite;
  animation: xfade 24s 22s infinite;
}

#slideshow:nthchild($i) {
  -webkit-animation: xfade 24s 21s infinite;
  animation: xfade 24s 21s infinite;
}

#slideshow:nthchild($i) {
  -webkit-animation: xfade 24s 20s infinite;
  animation: xfade 24s 20s infinite;
}

This is my desired result:

#slideshow .slide:nth-child(1) {
-webkit-animation: xfade 24s 18s infinite;
animation: xfade 24s 18s infinite;
}
#slideshow .slide:nth-child(2) {
-webkit-animation: xfade 24s 12s infinite;
animation: xfade 24s 12s infinite;
}
#slideshow .slide:nth-child(3) {
-webkit-animation: xfade 24s 6s infinite;
animation: xfade 24s 6s infinite;
}
#slideshow .slide:nth-child(4) {
-webkit-animation: xfade 24s 0s infinite;
animation: xfade 24s 0s infinite;
}

I didnt find any answers online that clearly said how to properly write @for loops. I found a bunch in the older .sass, but I dont know how to translate that to .scss since I'm a newbie.

Upvotes: 2

Views: 663

Answers (1)

Kees van Lierop
Kees van Lierop

Reputation: 1013

Assuming the output shows that the @for loop is placed inside the #slideshow selector, you should either move the for loop inside the .slide selector, or move the .slide selector in the for loop, depending on your preference:

#slideshow {
    @for $i from 1 through 4{
      & .slide:nthchild(#{$i}){
        animation: xfade 24s 24s - $i * 6 infinite;
      }
    }
}

or

#slideshow {
    .slide {
        @for $i from 1 through 4{
          &:nthchild(#{$i}){
            animation: xfade 24s 24s - $i * 6 infinite;
          }
        }
    }
}

Upvotes: 1

Related Questions