How To Loop Animation In Css

In this blog post, we will discover how to create a looping animation using only CSS. Animations can enhance the user experience on a website and add a level of interactivity that makes your site more engaging. With CSS, it is easy to create and control animations without any need for JavaScript.

Creating a Basic Animation

Before we dive into looping, let’s create a simple animation. We’ll start with a basic example: a square that moves from the left side of the screen to the right. First, let’s create the HTML structure with a simple div element:

    <div class="square"></div>
    

Now, let’s add some CSS to style the square and create the animation. We’ll use the @keyframes rule to define the animation and the animation property to apply it to the square:

    .square {
      width: 100px;
      height: 100px;
      background-color: blue;
      animation: moveRight 2s;
    }

    @keyframes moveRight {
      0% {
        transform: translateX(0);
      }
      100% {
        transform: translateX(300px);
      }
    }
    

In this example, we’ve created an animation called moveRight that moves the square from its starting position to 300px to the right. The animation lasts 2 seconds.

Making the Animation Loop

To make the animation loop, we just need to add the infinite keyword to the animation property in our CSS:

    .square {
      animation: moveRight 2s infinite;
    }
    

Now, the animation will loop indefinitely. However, you may notice that the animation jumps back to the starting position abruptly once it finishes. To make the animation loop smoothly, we can change the @keyframes rule to make the square return to its starting position:

    @keyframes moveRight {
      0%, 100% {
        transform: translateX(0);
      }
      50% {
        transform: translateX(300px);
      }
    }
    

Now, the square moves to the right and then back to the left, creating a smooth looping animation.

Controlling the Loop Count

If you want your animation to loop a specific number of times, you can replace the infinite keyword with an integer value. For example, to make the animation loop three times, you would do the following:

    .square {
      animation: moveRight 2s 3;
    }
    

In this example, the animation will play three times before stopping. You can adjust the loop count by changing the value.

Conclusion

Looping animations in CSS is simple and provides a powerful way to create engaging and interactive experiences on your website. With just a few lines of code, you can create smooth, professional-looking animations that loop indefinitely or a specific number of times. Have fun experimenting with different animations and loop counts to bring your website to life!