skip to Main Content

When animation-fill-mode is forwards and using Animation-Iteration-Count to repeat the animation, the animation resets after each iteration until the last, where animation-fill-mode seems to work.

I wanted to animate a div moving forward from 0px to 200px in two movements. When I made the animation, it moved 100px once, reset to 0px, then moved 100px again – it ended up at 100px rather than the intended 200px. I tested it on firefox and edge – neither worked. I wasn’t able to find anyone with my problem on google.

I intend to use this animation on multiple elements, but I want some to move forward more times than others. I’d prefer not to use JS.

I apologize for any inaccuracies in my question – this is my first time using stackoverflow.

div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation: animation 2s 2 forwards;
}

@keyframes animation {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100px);
  }
}
<div></div>

2

Answers


  1. Chosen as BEST ANSWER

    I've found a solution using JS. The problem apparently isn't animation-fill-mode forwards, it's the animation resetting the transform each time. If you instead use a script to set the transform differently every iteration, then add transitions, the problem is fixed.

    div = document.querySelector("div");
    console.log(div);
    i = 1;
    x = setInterval(() => {
      var transform = "translateX("+i*100+"px)";
      div.style.transform = transform;
      div.style.webkitTransform = transform;
      div.style.msTransform = transform;
      if (i==2) {
        clearInterval(x);
      }
      i++;
      console.log(div.style.transform);
    }, 1500);
    div {
      width:100px;
      height:100px;
      background-color:red;
      transition:transform 1s ease-in-out;
    }
    <div></div>


  2. You can remove the repetiton in animation and change the keyframe :

    div {
      width: 100px;
      height: 100px;
      background-color: red;
      animation: animation 2s forwards;
    }
    
    @keyframes animation {
      0% {
        transform: translateX(0);
      }
      50% {
        transform: translateX(100px);
      }
      100% {
        transform: translateX(200px);
      }
    }
    <div></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search