2

I have a two animations, one is a default animation that rotates a div on the z axis, and when you hover over the div, I have it scale up and down as well.

Is there a way for me to animate between the two animations? Currently if the animation is half way through, and I hover over the div it applies the new animation from the beginning, and it looks strange. I would like it to seamlessly go between animations is that possible?

.chest {
  height: 64px;
  width: 64px;
  background: yellow;
  animation: rocking-chest 2s linear infinite;
  
  margin-left: 50px;
  margin-top: 50px;
}

.chest:hover {
  animation: rocking-pulse-chest 1s linear infinite;
}

@keyframes rocking-chest {
  0% {
    transform: rotateZ(-20deg);
  }

  50% {
    transform: rotateZ(20deg);
  }

  100% {
    transform: rotateZ(-20deg);
  }
}

@keyframes rocking-pulse-chest {
  0% {
    transform: rotateZ(-20deg) scale(1);
  }

  50% {
    transform: rotateZ(20deg) scale(1.5);
  }

  100% {
    transform: rotateZ(-20deg) scale(1);
  }
}
<div class="chest"></div>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • Just ran into this about a week ago, and... afaik, nope. You'll probably end up just adding a transition and maybe running your animation with JS. +1 though, hoping there's a solution I missed. – sheng Mar 07 '19 at 15:33

2 Answers2

2

What about separating the zoom animation out onto an outer element whilst having an inner element do the rotation:

.chest {
  height: 64px;
  width: 64px;
  margin-left: 50px;
  margin-top: 50px;
}

.chest-inner {
  width: 100%;
  height: 100%;
  background: yellow;
  animation: rocking-chest 2s linear infinite;
}

.chest:hover {
  animation: scale-animation 1s linear infinite;
}

@keyframes rocking-chest {
  0% {
    transform: rotateZ(-20deg);
  }
  50% {
    transform: rotateZ(20deg);
  }
  100% {
    transform: rotateZ(-20deg);
  }
}

@keyframes scale-animation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.5);
  }
  100% {
    transform: scale(1);
  }
}
<div class="chest">
  <div class="chest-inner"></div>
</div>
Pete
  • 57,112
  • 28
  • 117
  • 166
1

You can animate width/height instead of scale and you will be able to have multiple animation that you can easily control. Of course, you won't have the same effect as using scale.

.chest {
  height: 64px;
  width: 64px;
  animation:
    rocking-pulse-chest 1s linear infinite paused,
    rocking-chest 2s linear infinite;
  margin-left: 50px;
  margin-top: 50px;
  background: yellow;
}

.chest:hover {
  animation-play-state:running ;
}

@keyframes rocking-chest {
  0%,100% {
    transform: rotateZ(-20deg);
  }

  50% {
    transform: rotateZ(20deg);
  }
}

@keyframes rocking-pulse-chest {
  50% {
    width:calc(64px * 1.5);
    height:calc(64px * 1.5);
    margin-left: calc(50px/1.5);
    margin-top: calc(50px/1.5);
  }

}
<div class="chest"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415