How to slide children at different speeds with CSS animation. Can this be done dynamically when # of children unknown?

Issue

I want to slide each of the children of the container element from right to left with the child elements completing the animation in order of top down.(item 1 completes animation then item 2, item3, etc.) How can I do this if the number of children is unknown?

<div class="container">
        <div class="child"> item 1</div>
        <div class="child"> item 2</div>
        <div class="child"> item 3</div>
        <div class="child"> item 4</div>
    </div>

I see a lot of guides on sliding from right to left on a single element. However, not seeing a way to slide individual items at various speeds, especially if the number of items is unknown.

Solution

If you know the max number of items, you can set animation times for each of the possible elements.

Then you’ll need to dynamically add a class to each element. Since the items are dynamically shown, I’m assuming you’re using something like map.

items.map((items, itemCount=0)=> {
   //code to append class with itemCount++ at end
}

Then in your CSS you can do something like this

.item1 {
  animation: 100ms slide-left;
}

.item2 {
  animation: 200ms slide-left;
}
.item3 {
  animation: 300ms slide-left;
}

@keyframes slide-left {
  from {
    margin-left: 100%;
  }
  to {
    margin-left: 0%;
  }
}

Notice how we can use the same animation and just change the timing on each child element to make it slide faster or slower.

Answered By – ltcrawsh

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.