A simple SCSS mixin to create staggered delays for a CSS animation.
Here's an example. Suppose you have a CSS class and keyframe
.fade-in {
animation: fade-in 1s ease-in-out;
}
@keyframes fade-in {
from {
opacity:0;
}
to {
opacity: 1;
}
}
and use it on an HTML div
<div class="item-container">
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
<div class="item fade-in"></div>
</div>
If you run this code, all 10 items would appear and animate at the same time.
Now if you want to stagger the animations, to have the items appear in sequence, you could write some CSS like this
.item:nth-of-type(2) {
animation-delay: .1s
}
.item:nth-of-type(3) {
animation-delay: .2s
}
.item:nth-of-type(4) {
animation-delay: .3s
}
.item:nth-of-type(5) {
animation-delay: .4s
}
.item:nth-of-type(6) {
animation-delay: .5s
}
.item:nth-of-type(7) {
animation-delay: .6s
}
.item:nth-of-type(8) {
animation-delay: .7s
}
.item:nth-of-type(9) {
animation-delay: .8s
}
.item:nth-of-type(10) {
animation-delay: .9s
}
Quite tedious and it's not going to scale well. So here's where my sass mixin comes in handy. Instead of writing the code above, you can simply copy paste the delays
mixin from the file above to your sass file and then add the one line of code in .fade-in
.fade-in {
animation: fade-in 1s ease-in-out;
@include delays(100, 0, 9);
}
The compiled CSS would look like this
.fade-in {
animation: fade-in 1s ease-in-out;
}
.fade-in.delay-100 {
animation-delay: 100ms
}
.fade-in.delay-200 {
animation-delay: 200ms
}
.fade-in.delay-300 {
animation-delay: 300ms
}
.fade-in.delay-400 {
animation-delay: 400ms
}
.fade-in.delay-500 {
animation-delay: 500ms
}
.fade-in.delay-600 {
animation-delay: 600ms
}
.fade-in.delay-700 {
animation-delay: 70ms
}
.fade-in.delay-800 {
animation-delay: 800ms
}
.fade-in.delay-900 {
animation-delay: 900ms
}
and all you have to do is specify the correct class names in your html file
<div class="item-container">
<div class="item fade-in"></div>
<div class="item fade-in delay-100"></div>
<div class="item fade-in delay-200"></div>
<div class="item fade-in delay-300"></div>
<div class="item fade-in delay-400"></div>
<div class="item fade-in delay-500"></div>
<div class="item fade-in delay-600"></div>
<div class="item fade-in delay-700"></div>
<div class="item fade-in delay-800"></div>
<div class="item fade-in delay-900"></div>
</div>
Here we go