csssass

infinite scss class loop


I have this code that generates 5 item classes

  @for $num from 1 through 5 {
    .item-#{$num} {
      transform-origin: top center;
      animation: rotateX 300ms ($num * 60ms) ease-in-out forwards;
    }
    .item-#{$num} + .item-last {
      transform-origin: top center;
      animation: rotateX 300ms (($num + 1) * 60ms) ease-in-out forwards;
    }
  }

but if i create 6 or more items it does not work..

how can i make it go by my items count instead of constant 5? or may be some different way.


Solution

  • Better to use JS for a use case like this. It will work with however many divs you have (infinite like you want) but it will not bloat your stylesheet to infinite file size. I had to guess a little bit about your HTML structure.

    document.querySelectorAll("[class^='item-']").forEach((item, index) => {
       item.style.animation = `rotateX 300ms ${index * 60}ms ease-in-out forwards`;
       const nextSibling = item.nextElementSibling;
       if(nextSibling){
         nextSibling.style.animation = `rotateX 300ms ${(index + 1) * 60}ms ease-in-out forwards`;
       }
    })
    [class^=item-] {
          height: 40px;
          width: 40px;
          background: blue;
          transform-origin: top center;
    }
    
    .last-item {
          height: 40px;
          width: 40px;
          background: pink;
          transform-origin: top center;
    }
    
    @keyframes rotateX {
     0% {
      transform: rotate(0deg);
     }
     
     100% {
      transform: rotate(-90deg);
     }
    
    }
    <div class="item-1"></div>
    <div class="last-item"></div>
    <div class="item-2"></div>
    <div class="last-item"></div>
    <div class="item-3"></div>
    <div class="last-item"></div>
    <div class="item-4"></div>
    <div class="last-item"></div>
    <div class="item-5"></div>
    <div class="last-item"></div>