CSS3 Rotate Animation

Nikk picture Nikk · May 27, 2013 · Viewed 737.3k times · Source
<img class="image" src="" alt="" width="120" height="120">

Cannot get this animated image to work, it is supposed to do a 360 degrees rotation.

I guess something's wrong with the CSS below, as it just stays still.

.image {
    float: left;
    margin: 0 auto;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 120px;
    height: 120px;
    margin-top: -60px;
    margin-left: -60px;

    -webkit-animation-name: spin;
    -webkit-animation-duration: 4000ms;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;

    -moz-animation-name: spin;
    -moz-animation-duration: 4000ms;
    -moz-animation-iteration-count: infinite;
    -moz-animation-timing-function: linear;

    -ms-animation-name: spin;
    -ms-animation-duration: 4000ms;
    -ms-animation-iteration-count: infinite;
    -ms-animation-timing-function: linear;

    animation-name: spin;
    animation-duration: 4000ms;
    animation-iteration-count: infinite;
    animation-timing-function: linear;

    @-ms-keyframes spin { 
        from { 
            -ms-transform: rotate(0deg); 
        } to { 
            -ms-transform: rotate(360deg); 
        }
    }
    @-moz-keyframes spin { 
        from { 
            -moz-transform: rotate(0deg); 
        } to { 
            -moz-transform: rotate(360deg); 
        }
    }
    @-webkit-keyframes spin { 
        from { 
            -webkit-transform: rotate(0deg); 
        } to { 
            -webkit-transform: rotate(360deg); 
        }
    }
    @keyframes spin { 
        from { 
            transform: rotate(0deg); 
        } to { 
            transform: rotate(360deg); 
        }
    }
}

Answer

Giona picture Giona · May 27, 2013

Here is a demo. The correct animation CSS:

.image {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 120px;
    height: 120px;
    margin:-60px 0 0 -60px;
    -webkit-animation:spin 4s linear infinite;
    -moz-animation:spin 4s linear infinite;
    animation:spin 4s linear infinite;
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
<img class="image" src="http://i.stack.imgur.com/pC1Tv.jpg" alt="" width="120" height="120">


Some notes on your code:

  1. You've nested the keyframes inside the .image rule, and that's incorrect
  2. float:left won't work on absolutely positioned elements
  3. Have a look at caniuse: IE10 doesn't need the -ms- prefix