burebistaruler burebistaruler - 21 days ago 6
CSS Question

less mixin looping classes but with different values

I have this mixin:

.myClass {
.nth(1);
.nth(2);
.nth(@i) {
&:nth-of-type(@{i}) {
transition-delay: 0.2s;
}
}
}


that is compiling in something like:

.myClass:nth-of-type(1) {
transition-delay: 0.2s;
}
.myClass:nth-of-type(2) {
transition-delay: 0.2s;
}


my question is how to add different values for
transition-delay
because in this form will repeat the same value and I need to be able to add different values and to compile something like:

.myClass:nth-of-type(1) {
transition-delay: 0.5s;
}
.myClass:nth-of-type(2) {
transition-delay: 0.02s;
}


and so on...

Answer

Since you are not using looping but is simply calling the mixin with the required numbers, you could add an extra parameter for the delay value in the mixin definition and use it like in below code block:

.myClass {
  .nth(1; 0.2s);
  .nth(2; 0.5s);
  .nth(@i; @delay) {
    &:nth-of-type(@{i}) {
      transition-delay: @delay;
    }
  }
}

Or you could use a loop and an array like in the below code block: (I'd recommend this just because you don't need multiple mixin calls.)

@delays: 0.2s, 0.5s, 0.75s;
.myClass {
  .nth-loop(@i; @delays) when (@i > 0){
    @delay: extract(@delays, @i); /* take the delay value corresponding to element number from array */
      &:nth-of-type(@{i}) {
        transition-delay: @delay;
      }
    .nth-loop(@i - 1; @delays);
  }
  .nth-loop(3; @delays);
}