Lodve Grodal
Lodve Grodal

Reputation: 21

CSS Animation w/ keyframes

I'm trying to make an animation where a picture moves to left and to the right in a loop. By using keyframes I've achieved this, but my next step was to transform:scaleX(-1) the image instantly when the image reaches 25% and 50% and so on.. All help is appreciated!

div.container {
  background-color: grey;
  height: 500px;
  position: relative;
  width: 500px;
}

div.object {
  animation-name: move;
  animation-duration: 4s;
  animation-iteration-count: infinite;
  background-color: red;
  height: 150px;
  left: 40px;
  position: absolute;
  width: 150px;
}

@keyframes move {
  0% {
    left: 40px;
  }
  25% {
    left: -60px;
  }
  50% {
    left: 40px;
  }
  75% {
    left: -60px;
  }
  100% {
    left: 40px;
  }
}
<div class="container">
  <div class="object"></div>
</div>

Upvotes: 1

Views: 60

Answers (1)

Martin
Martin

Reputation: 16423

I'm not clear about how you want to use transform: scaleX(-1); in your animation, but the principle of what you are looking to achieve is definitely valid.

Essentially, my understanding is that you want to run the animation that moves your element, and at specific intervals immediately apply a transform without it being gracefully animated.

In order to achieve this, add a second animation and run it along-side the first:

animation: move 4s infinite, transformScale 4s infinite;

@keyframes transformScale {
  0% {
    transform: scaleX(-0.25);
  }
  25% {
    transform: scaleX(0.5);
  }
  50% {
    transform: scaleX(-0.25);
  }
  75% {
    transform: scaleX(0.5);
  }
  100% {
    transform: scaleX(-0.25);
  }
}

Of course, this will run exactly as the first animation, with the transition between keyframes. The solution is to use:

animation-timing-function: steps(1, end);

Which results in the animation CSS of:

animation: move 4s infinite, transformScale 4s infinite steps(1, end);

Here's a snippet that shows it in action.

div.container {
  background-color: grey;
  height: 500px;
  position: relative;
  width: 500px;
}

div.object {
  animation: move 4s infinite, transformScale 4s infinite steps(1, end);
  background-color: red;
  height: 150px;
  left: 40px;
  position: absolute;
  width: 150px;
}

@keyframes move {
  0% {
    left: 40px;
  }
  25% {
    left: -60px;
  }
  50% {
    left: 40px;
  }
  75% {
    left: -60px;
  }
  100% {
    left: 40px;
  }
}

@keyframes transformScale {
  0% {
    transform: scaleX(-0.25);
  }
  25% {
    transform: scaleX(0.5);
  }
  50% {
    transform: scaleX(-0.25);
  }
  75% {
    transform: scaleX(0.5);
  }
  100% {
    transform: scaleX(-0.25);
  }
}
<div class="container">
  <div class="object"></div>
</div>

Upvotes: 1

Related Questions