Techstacker
Light ModeDark ModeReset dark mode. Falls back to OS dark mode setting.

Pages

No results for 'undefined'

Blog Posts

No results for 'undefined'
Powered by Algolia

How to Use CSS Animations to Rotate Images Continuously

Oct 21, 20192 min readCSS, AnimationViews:

In this quick tutorial, you’ll learn how to continuously rotate images using the CSS animation property.

First, we need some HTML markup with an image and some attributes:

<img src="https://upload.wikimedia.org/wikipedia/en/7/77/EricCartman.png" class="rotate linear infinite" width="150" height="150" />

Your image should show up like this:

As you can see our image element has three classes, rotate, linear and infinite. In our CSS stylesheet we need to create a declaration block for each class. These types of classes are sometimes called utility or helper classes, but I prefer the term single-purpose because it’s more descriptive.

First let’s declare the .rotate code block:

.rotate {
  animation: rotation 2s;
}

Nothing will happen yet, because we need to define the animation property’s rotation function. Add this CSS keyframe rule to your stylesheet:

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

Now if you reload your browser tab, you should see your image rotating a single time over 2 seconds (2s). But we need to do two more things. We want the image to rotate continuously, and we want to change the animation transition timing from the default ease to a consistent speed curve, called linear.

Add this .linear declaration block to your CSS stylesheet:

.linear {
  animation-timing-function: linear;
}

Reload your browser tab and you’ll see that your image is now spinning at a consistent speed rate from start to end.

Lastly, let’s make our image rotate infinitely by declaring our .infinite class’s code block:

.infinite {
  animation-iteration-count: infinite;
}

And voila, you now have an infinitely/continuously spinning image with a linear animation speed curve.

Check out the complete code on CodePen

Note: we could have declared all our animation properties in a single line and a single class, like this:

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

The above saves a lot of code, but for learning/teaching, I prefer to break things down to smaller bites, because makes it easier to understand how individual components work together.

There many animations curves beside the default ease and the linear that we use here. You can get really fancy using a cubic-bezier animation curve, but that’s for a different tutorial.

Check out the Mozilla’s CSS Animation section if you more insight into what’s possible with CSS animations.