Why hover doesn't work on my css animation?

294 Views Asked by At

Hi guys I am new here and have a problem. So no hate please.

I have here an animation that swings every 2.5s. However, this should also swing when I hover over it. However, only one of the two goes. What have I done wrong? Could someone help?

Thanks in advance enter image description here

1

There are 1 best solutions below

0
Lars On

The animation's transform will overwrite the one in :hover. It will not apply any meaningful change.

There's a couple of options to work around that:

  • Replace the animation, when a new animation is applied, this enforces a restart of the animation
  • Add a wrapper and animate that

The wrapper might as well be invisible (without padding/border/background). And you might want to remove the animation of the child so it doesn't double animate.

.contact_example__mover {
  display: flex;
  flex-direction: column;
  transform-origin: top center;
  transform-style: preserve-3D;
  animation: swing ease-in-out 1.5s infinite alternate;
}

.contact_example__mover.overwrite-animation:hover {
  animation: swing-hover ease-in-out 1.5s infinite alternate;
}

.wrapper {
  display: inline-block;
  transition: transform .25s;
  transform-origin: top center;
  transform-style: preserve-3D;
  padding: .5rem;
  background-color: teal;
}

.wrapper:hover {
  transform: rotate(-45deg);
}

.wrapper.and-remove-animation:hover .contact_example__mover {
  animation: none;
}

@keyframes swing {
  0% {
    transform: rotate(0deg);
  }
  20% {
    transform: rotate(-45deg);
  }
  40% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes swing-hover {
  0% {
    transform: rotate(0);
  }
  20% {
    transform: rotate(-45deg)
  }
  40% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

.contact_example__mover {
  background-color: olive;
  padding: 1rem;
  text-align: center;
  color: bisque;
  width: 4rem;
  height: 4rem;
}
Overwrite with similar animation:
<div class="contact_example__mover overwrite-animation">set new animation</div>
<br>
<br> Add wrapper and transform that.<br>
<div class="wrapper">
  <div class="contact_example__mover">wrap with animation</div>
</div>
<br>
<br> Add wrapper and also remove animation from child. <br>
<div class="wrapper and-remove-animation">
  <div class="contact_example__mover">wrap with animation</div>
</div>