Search code examples
htmlcssclasscss-transitionsfadein

how to target the same animation with different delays


I have two divs that contain a word each. And each letter in each of those words is inside a span tag like so:

<div class="fade-in">
   <span>h</span><span>e</span><span>l</span><span>l</span><span>o</span>
</div>

<div class="fade-in">
   <span>w</span><span>o</span><span>r</span><span>l</span><span>d</span>
</div>

In my css file, I have created an animation that fades in the words like so:

.fade-in span{
  opacity: 0;
  animation-name: fadeInOpacity;
  animation-iteration-count: 1;
  animation-timing-function: ease-in;
  animation-duration: 2s;
  animation-fill-mode: forwards;
}

@keyframes fadeInOpacity {
  0% {opacity: 0;}
  100% {opacity: 1;}
}

and then added a delay to get the letters fading in order, like so:

.fade-in span:nth-child(1)  { animation-delay: 400ms; }
.fade-in span:nth-child(2)  { animation-delay: 500ms; }
.fade-in span:nth-child(3)  { animation-delay: 600ms; }
.fade-in span:nth-child(4)  { animation-delay: 700ms; }
.fade-in span:nth-child(5)  { animation-delay: 800ms; }

Ok so this works, but both words start fading in at the same time. What I would like is for the first letter of the second word to start fading in after the last letter of the first word. I am very new to development but I am guessing there has to be a better way than creating new animations.

Is there a way to add different delays to the same animation and target different classes or id's? Thanks for your time.


Solution

  • HTML:

        <div class="fade-in" id="hello">
        <span>h</span><span>e</span><span>l</span><span>l</span><span>o</span>
        </div>
    
        <div class="fade-in" id="world">
        <span>w</span><span>o</span><span>r</span><span>l</span><span>d</span>
        </div>      
    

    CSS:

        #hello .fade-in span:nth-child(1)  { animation-delay: 300ms; }
        #hello .fade-in span:nth-child(2)  { animation-delay: 400ms; }
        #hello .fade-in span:nth-child(3)  { animation-delay: 500ms; }
        #hello .fade-in span:nth-child(4)  { animation-delay: 600ms; }
        #hello .fade-in span:nth-child(5)  { animation-delay: 700ms; }
    
    
        #world .fade-in span:nth-child(1)  { animation-delay: 900ms; }
        #world .fade-in span:nth-child(2)  { animation-delay: 1000ms; }
        #world .fade-in span:nth-child(3)  { animation-delay: 1100ms; }
        #world .fade-in span:nth-child(4)  { animation-delay: 1200ms; }
        #world .fade-in span:nth-child(5)  { animation-delay: 1300ms; }