crg
crg

Reputation: 4557

How to run two CSS animations at the same time?

I would like to execute two aniamtion, without stopping the first.

I'll show you it will be easier. Here is my code :

animation: hover  7s, shake .2s 3s infinite;

I have two animations called hover and shake. The shake one should be executed after 3s so during the first one hover because this one has a time set of 7s.

The goal of it is to have at the end a circle getting smaller and shaking at the same time.

But what it does it's when shake starts it stops hover even thaugt hover should have 4s left.

Any idea to solve that issue? I tried to make all animation at once, but it didn't work correctly.

Am i obliged to make only one animation instead of two ?

Here is the code of animations :

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%, 80% {
    transform: translate3d(1px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-3px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(3px, 0, 0);
  }
}

@keyframes hover {
  0% {
    transform: scale(1);
  }
  30% {
    transform: scale(1.3);
  }
  100% {
    transform: scale(0.3);
  }
}

Upvotes: 0

Views: 221

Answers (1)

Alessio
Alessio

Reputation: 3620

The problem is that the second style rule hides the first because they are both acting on the transform property.

Wrap your element into a div and give the parent an animation ("hover") and the child another one ("shake"). Note that you have set a 3s delay to the "shake" animation.

.hover {
  animation: hover 7s infinite running;
}

.cursor {
  animation: shake .2s 3s infinite running;
  &:after {
    opacity: 1;
  } 
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%, 80% {
    transform: translate3d(1px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-3px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(3px, 0, 0);
  }
}

@keyframes hover {
  0% {
    transform: scale(1);
  }
  30% {
    transform: scale(1.3);
  }
  100% {
    transform: scale(0.3);
  }
}

.parent {
  height: 25px;
  width: 25px;
  left: 0;
  right: 0; 
  top:0;
  bottom: 0;
  margin: auto;
}

.cursor {
  height: 25px;
  width: 25px;
  border-radius: 50%;
  position: absolute;
  left: 0;
  right: 0; 
  top:0;
  bottom: 0;
  margin: auto;
  border: 1px solid #293133;
    &:after {
    content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    border-radius: 50%;
    opacity: .5;
  }
}
<div class="parent hover">
  <div class="cursor"></div>
</div>

Here's a working Codepen

Upvotes: 2

Related Questions