How to create a loading spinner using CSS3 animations

Hi guys! Yesterday I’ve been playing and designing some loading gifs concepts. Now I’m sharing with you an easy method to recreate that animations using CSS3. This is the final result:

For those impatient people, I’ve created a online working demo on dabblet. Let’s take a quick look to the CSS code:

.loader {
	width: 32px; height: 32px; display: inline-block;
	font: 0/0 a; text-shadow: none; color: transparent; /*font hack replacement*/
	background: transparent url(http://f.cl.ly/items/1J161J3L0A2x0c1r303O/loader.gif) left top no-repeat;
	-webkit-animation: 'animation' 1s steps(10, end) infinite;
	-moz-animation:    'animation' 1s steps(10, end) infinite;
}

@-webkit-keyframes animation { from { background-position: 0 0; } to { background-position: 100% 0; } }
@-moz-keyframes animation    { from { background-position: 0 0; } to { background-position: 100% 0; } }

I’m using a css sprite as background-image so I can make use of CSS3 animations to recreate the loading spinner varying the background position in 10 steps and it works perfectly on modern browsers.

That’s a great solution but… what about Internet Explorer? In this case we have an easy solution: use a real gif image as background. I didn’t make it but you have a lot of options:

  • Conditional CSS stylesheets
  • Hack selectors
  • Real fallback for old browsers, using non supported properties

Real fallback? Yes, for example we could type this:

background: url(loading.gif) no-repeat;
background: url(loading-sprite.png) left top / 100% 100% no-repeat;

So old browsers will validate the last supported property (in this case the first one) and new browsers will load the second one because their support for background-size 100% 100%.

Hope you find it useful!

View online demo and source code →

One Comment

Got something to say? Feel free, I want to hear from you! Leave a Comment

  1. angel says:

    looks great great! i will use some like this in the next freelance project, thanks for share!

Leave a Comment

Got something to say? Feel free, I want to hear from you!