Liam
Liam

Reputation: 9855

Iterate variables in SCSS?

I'm writing a function to fade items in, in sequence...

.sequenced-images li:nth-child(2) {
  animation-delay: 1s;
}
.sequenced-images li:nth-child(3) {
  animation-delay: 2s;
}
.sequenced-images li:nth-child(4) {
  animation-delay: 3s;
}
.sequenced-images li:nth-child(5) {
  animation-delay: 4s;
}

I have a lot of items and I don't want to have to manually keep adding a class for the next item.

Can I iterate over the same rule using something like...

.sequenced-images li:nth-child(i++) {
  animation-delay: i++s;
}

?

Upvotes: 0

Views: 88

Answers (1)

juzraai
juzraai

Reputation: 5943

Yes, you can use for loop and string interpolation:

@for $i from 2 through 5 {
  .sequenced-images li:nth-child(#{$i}) {
    animation-delay: '#{$i - 1}s';
  }
}

This will result in:

.sequenced-images li:nth-child(2) {
  animation-delay: "1s";
}

.sequenced-images li:nth-child(3) {
  animation-delay: "2s";
}

.sequenced-images li:nth-child(4) {
  animation-delay: "3s";
}

.sequenced-images li:nth-child(5) {
  animation-delay: "4s";
}

Upvotes: 6

Related Questions