How to continuously rotate an image using CSS

By

Learn how to continuously rotate an image, or any HTML element, using CSS animations and a keyframes rule that spins it from 0 to 360 degrees on a loop.

~~~

To continuously rotate an image with CSS you need two things: an animation property on the element, and a @keyframes rule that spins it from 0 to 360 degrees. No JavaScript involved.

While building the React Handbook landing page, I had to search how to rotate an image. I wanted to rotate an SVG image, but this works for any image type. Or any HTML element, actually.

Add this CSS instruction to the element you want to rotate:

animation: rotation 2s infinite linear;

You can also choose to add a rotate class to an element, instead of targeting it directly:

.rotate {
  animation: rotation 2s infinite linear;
}

Then add this line, outside of any selector:

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

That’s it! Your element should now rotate.

What does each part of the shorthand mean?

animation is a shorthand for several properties. In our case:

That last value matters more than it looks. The default timing function is ease, which starts slow, speeds up, and slows down again. On a loop, that produces a visible stutter at the start of every turn. linear keeps the speed constant, so the spin looks continuous.

The keyframes rule describes the movement itself: at the start the element is rotated 0 degrees, at the end 359. The browser fills in every frame in between. You can use 360deg too; with a linear timing function both look the same, because the end frame lines up with the start of the next loop.

By default the element rotates around its own center. If you want it to spin around a different point, set transform-origin on the element.

Why is my element not rotating?

Be careful if you apply this to a span or a link: CSS transforms don’t work on inline elements. Images are fine, since they’re replaced elements, but for inline text elements you need to add:

display: inline-block;

After that, the rotation kicks in.

Check out the CSS Animations and CSS Transitions guides

Here is the result shown in Codepen:

See the Pen How to use CSS Animations to continuously rotate an image by Flavio Copes (@flaviocopes) on CodePen.

Tagged: CSS · All topics
~~~

Related posts about css: