I am trying to create a cascading effect by applying an animation to each child element. I was wondering if there is a better way to do it than this:
.myClass img:nth-child(1){ -webkit-animation: myAnimation 0.9s linear forwards; } .myClass img:nth-child(2){ -webkit-animation: myAnimation 0.9s linear 0.1s forwards; } .myClass img:nth-child(3){ -webkit-animation: myAnimation 0.9s linear 0.2s forwards; } .myClass img:nth-child(4){ -webkit-animation: myAnimation 0.9s linear 0.3s forwards; } .myClass img:nth-child(5){ -webkit-animation: myAnimation 0.9s linear 0.4s forwards; }
and so on... So basically, I'd like to have an animation starting for each child but with a delay. Thanks for any input!
Addition: Maybe I did not properly explain what was my concern: It's about how to do this no matter how many children I have. How to do this without having to write down the properties for every child... for example, when I don't know how many children there are going to be.
The CSS animation-delay property has the following syntax: animation-delay: [time] | initial | inherit; As you can see, there are three possible values: time, initial, and inherit. The first option is [time], which is the number of seconds or milliseconds before the animation starts.
CSS Demo: transition-delay A value of 0s (or 0ms ) will begin the transition effect immediately. A positive value will delay the start of the transition effect for the given length of time. A negative value will begin the transition effect immediately, and partway through the effect.
The animation-delay CSS property specifies the amount of time to wait from applying the animation to an element before beginning to perform the animation. The animation can start later, immediately from its beginning, or immediately and partway through the animation.
Here's a scss way to do it using a for loop.
@for $i from 1 through 10 { .myClass img:nth-child(#{$i}n) { animation-delay: #{$i * 0.5}s; } }
What you want is the animation delay property.
@keyframes FadeIn { 0% { opacity: 0; transform: scale(.1); } 85% { opacity: 1; transform: scale(1.05); } 100% { transform: scale(1); } } .myClass img { float: left; margin: 20px; animation: FadeIn 1s linear; animation-fill-mode: both; } .myClass img:nth-child(1) { animation-delay: .5s } .myClass img:nth-child(2) { animation-delay: 1s } .myClass img:nth-child(3) { animation-delay: 1.5s } .myClass img:nth-child(4) { animation-delay: 2s }
<div class="myClass"> <img src="http://placehold.it/200x150" /> <img src="http://placehold.it/200x150" /> <img src="http://placehold.it/200x150" /> <img src="http://placehold.it/200x150" /> </div>
A CSS preprocessor such as Less.js or Sass can reduce the amount of repetition, but if you're working with an unknown number of child elements or need to animate a large number then JavaScript will be the best option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With