Loading Spinners with CSS instead of GIFs

May 08, 2018

Communicating the state of different parts of your application is one of the cornerstones when providing a good experience for your users. This is especially true when more functionality is moved client-side and we can't rely on the browser to show the user that something is happening.

The go-to solution in many cases is to show a spinner when something is loading or being processed. Historically, I've usually used an image tag to display a GIF with a spinner. But the other day I realized that the same results can easily be achieved with an icon and some CSS animations.

Using a CSS approach makes the spinner way easier to customize and reduces the number of requests you have to do on page load(if you are already loading an icon set).

I'm going to use ionicons for this example and they have four loading icons to chose from.

First I add an icon to the markup with the rotates class

<i class="icon ion-load-c rotates"></i>

Then I define the animation.

.rotates {
  display: inline-block;
  line-height: 0;
  -webkit-animation: spin 1.3s infinite linear;
  animation: spin 1.3s infinite linear;
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(359deg);
    transform: rotate(359deg);
  }
}

@keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(359deg);
    transform: rotate(359deg);
  }
}

Using either display: block or display: inline-block allows me to use transform to rotate the icon. Setting the line-height to zero makes sure that the pivot point is at the center of the icon which results in a smoother rotation.

I find the uniform rotation speed a bit boring so reducing the duration and adding a bit of easing gives it some more "weight".

  animation: spin 1.2s infinite ease-in-out;

See the Pen MGrOZY by Christoffer Artmann (@Artmann) on CodePen.

Christoffer Artmann