Search code examples
cssanimationrotationtransformkeyframe

CSS Combining Animations - Second Animation Not Behaving As Expected


I am trying to add multiple CSS keyframe animations to a single object. I have an image of a rocket that I want to move right across the screen, and then rotate up to right itself. The first part, moving right, is working fine. The second part, rotating, seems to be working, but instead of rotating in place, it rotates while it moves back to the left.

Here is how it currently looks:

https://codeeverydamnday.com/projects/rocketblaster/index2.html

Relevant HTML:

<img id="rocketfire" src="images/rocketfireright.svg" />

Relevant CSS:

#rocketfire {
  position: absolute;
  top: 200px;
  left: -320px;
  height: 200px;
  animation: 
    launch 4s ease-in-out 0.5s 1 forwards,
    rightself 2s ease-in-out 4.5s 1 forwards;
}

@keyframes launch {
  0% {transform: translateX(-320px);}
  100% {transform: translateX(1050px);}
}

@keyframes rightself {
  100% {transform: rotate(-90deg);}
}

Every tutorial I have watched has said the same thing—just comma-separate the animations and add the properties you'd like, making sure to add a delay so the second animation doesn't start until after the first. Use "forwards" to keep the object in the ending state of the animation.

I have done all this, but can't figure out why the rotate animation is also moving the object back to the left side instead of just rotating in place. Am I missing something?


Solution

  • It works if you change the animation rightself to this:

    @keyframes rightself {
      100% {
        transform: translateX(1050px) rotate(-90deg);
      }
    }
    

    I think the animation is not able to retain state but I can't figure why.