N Kaushik

How to rotate an image continuously using css

August 07, 2021

How to rotate an image continuously using css:

css animations are easy to use and makes our life a lot easier. We can rotate anything like an image or any other components using only css. Just add a few lines of code and it will keep rotating the object.

You can use this code to any HTML component, not only for image.

rotation property of css:

Below is the complete example that rotates an image continuosly:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      .rotateImage {
        height: 100px;
        width: 100px;
        animation: rotation infinite 2s linear;
      }

      @keyframes rotation {
        from {
          transform: rotate(0deg);
        }

        to {
          transform: rotate(360deg);
        }
      }
    </style>
    <meta charset="UTF-8" />
    <title>Test</title>
  </head>
  <body>
    <img
      src="https://cdn.pixabay.com/photo/2013/07/13/10/51/football-157930_1280.png"
      class="rotateImage"
    />
  </body>
</html>

rotateImage is the class that defines the rotation. The animation property defines the animation type. We are using rotation animation. It runs for infinite amount of time. It completes one rotation in 2 seconds and it is a linear animation,i.e. the animation will run at same speed from start to finish.

We also need to add the @keyframes below the class to define the start and end position for the rotation.

The rotataion starts at 0 degree and ends at 360 degrees.

The above code will give the below output:

rotate image html css

Rotating in Anticlockwise direction:

The above code rotates the image in clockwise direction. We can also change it to rotate in anticlockwise direction by simply changing the start and end angles.

You need to do the following change for that:

@keyframes rotation {
    from {
        transform: rotate(360deg);
    }

    to {
        transform: rotate(0deg);
    }
}

It will start rotating the image in anticlockwise.

You can also use this trick to rotate any other html components.


Subscribe to my Newsletter