I’m going to start with a regular stationary ball

.ball{
  width: 100px;
  height: 100px;
  border-radius: 100px;
  background-color: #f69;
}
Copy the code

Then add a magical transform property that shifts the ball away from its original position.

.ball{
  /* ...  */
  transform: translate(200px.0);
}
Copy the code

Transition: Motion triggered, one-time animation

Get it moving

.ball{
  /* ...  */
  transform: translate(200px.0);
  transition: 1s linear;
}
.ball:hover{
  /* ...  */
  transform: translate(0.0);
}
Copy the code

But the trouble with transition is that it has to hover active in some way, and then animate once.

For more complex animations, you need an animation

Animation: It can be triggered at any time with strong controllability

Change the above to animation:

  .ball {
    width: 100px;
    height: 100px;
    border-radius: 100px;
    background-color: #f69;
    animation: move 2s linear;
  }

  @keyframes move {
    0% {
      transform: translate(0.0);
    }
    100% {
      transform: translate(200px.0); }}Copy the code

The ball moves at the beginning, but after the movement, it returns to the position before the animation, which is a very sudden feeling. If you want to change it, there are two ways:

  • The first common way to do this is to set 100% of the animation to be the state before the animation, so that it ends exactly as it was before the animation.
  @keyframes move {
    0%.100% {
      transform: translate(0.0);
    }
    50% {
      transform: translate(200px.0); }}Copy the code
  • Second: set animation fill modeforwardsWhen the animation is over, leave the ball at 100%
/* Backwards is used to move the balls in 0% state before animation starts. Both is a 0% and a 100% state */ before and after the animation
.box{animation: move 2slinear forwards; }Copy the code

The introduction of 8 properties of Animation of Daniel Yao is very good

Infinite play: Basic combination with alternative

Implementation is always moving

.ball {
  width: 100px;
  height: 100px;
  border-radius: 100px;
  background-color: #f69;
  /* Alternate is critical, forward and reverse, first from 0%->100%, then 100%->0%, so that there is always moving effect */
  animation: move 2s linear alternate infinite;
}

@keyframes move {
  0% {
    transform: translate(0.0);
  }
  100% {
    transform: translate(200px.0); }}Copy the code