Search code examples
csssasscss-animations

Sass for loop assigns same index to each element


I want to apply an animation to different divs. Each of them should get their own animation delay.

There are many tutorials online (Like this one) and I followed them closely, but for some reason the animation delay remains the same for every div.

I have the following for loop:

@for $i from 1 through 5 {
    #contact-grid .contact-item .contact-link:nth-child(#{$i}) {
        @include textShakeAnimation($delay: #{$i}s);
    }
}

With this animation mixin:

@mixin textShakeAnimation($delay) {
    transform-origin: center;
    animation-name: text-shake;
    animation-duration: 8s;
    animation-delay: $delay;
    animation-iteration-count: infinite;
}

@keyframes text-shake {
    0% {transform: rotate(0deg);}
    2% {transform: rotate(5deg);}
    4% {transform: rotate(-5deg);}
    6% {transform: rotate(5deg);}
    8% {transform: rotate(-5deg);}
    10% {transform: rotate(5deg);}
    12% {transform: rotate(0deg);}
    100% {transform: rotate(0deg);}
}

The relevant HTML looks like this:

<div id="contact-grid">
    <div class="contact-item">
        <div class="contact-header-wrapper">
            <i class="fa-brands fa-twitter contact-icon fa-2x"></i>
            <h3 class="contact-heading">Twitter</h3>
        </div>
        <p class="contact-text">Check us out on Twitter!</p>
        <div class="contact-link">
            <a href="#">@kitis_kitties</a>
        </div>
    </div>
    ...
</div>

What is strange to me is, that despite the loop going from 1 to 5, when I inspect the divs, the animation delay for every div is 3. So right at the midpoint of the indexes.

But the strangest thing is, that the generated CSS has the correct animation delays:

#contact-grid .contact-item .contact-link:nth-child(1) {
  transform-origin: center;
  animation-name: text-shake;
  animation-duration: 8s;
  animation-delay: 1s;
  animation-iteration-count: infinite; }
...

The animation itself is working well, but the delays are not applied correctly.

Does anyone have an idea what I am missing? Or at least some pointers in the right direction?

Thanks in advance.


Solution

  • it is due to incorrect targetting of css, :nth-child should be on .contact-item instead of .contact-link

    //your code
        @for $i from 1 through 5 {
            #contact-grid .contact-item .contact-link:nth-child(#{$i}) {   
                @include textShakeAnimation($delay: #{$i}s);
            }
        }
    
    //corrected code
            @for $i from 1 through 5 {
                #contact-grid .contact-item:nth-child(#{$i}) .contact-link{  //this line
                    @include textShakeAnimation($delay: #{$i}s);
                }
            }