user3658794
user3658794

Reputation: 769

How do you spin side to side using css3 animation?

I have an image of a face. I want to spin/rotate it side to side. 20 degrees to the right and 20 degrees to the left.

So far this is my code:

<img class="image"> 

CSS

.image {

-webkit-animation:spin 1.8s linear infinite;

}

@-webkit-keyframes spin {

from { -webkit-transform: rotate(0deg); }
to { -webkit-transform: rotate(20deg); }

}

I can get it to move one way, but how do I make it go back the other way?

I was thinking it should work like this: spin from 0 deg to 20 deg from 20 deg to -20 degrees. I tried it but it doesn't work.

Upvotes: 1

Views: 2509

Answers (1)

Harry
Harry

Reputation: 89760

You would not be able to achieve it using from and to in animations but you can use the percentage option like below:

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

Explanation:

  • For the first 50% of the animation duration (0-0.9s), it would rotate the image from 0 to 20 degrees.
  • For the next 50% (50% - 100%), it would rotate the image from 20 degrees to -20 degrees.
  • For the animation to have a more smoother look, you could also a rotate to 0 degree in between and at the end (as shown in Sample 2 below).
  • If you want 0 to 20 alone to happen in a 1.8s window and 20 to -20 degrees to take another 1.8s then you can increase the animation duration to 3.6s in the -webkit-animation property value like below (at the end).

Note: I assume you are aware that with the -webkit- prefix, the animation effect would be seen only in webkit powered browsers. For Firefox, you would have to add -moz- for the animations, keyframes and transform properties and for future compliance you would have to add the standard un-prefixed versions also.

.image {
    -webkit-animation:spin 3.6s linear infinite;
}

Fiddle Demo


Sample 2 - with a smoother rotation effect

@-webkit-keyframes spin {
    0% {
        -webkit-transform: rotate(0deg);
    }
    25% { /* note that rotation from 0 to 20 deg happens in 25% time = 0.45 seconds. */
        -webkit-transform: rotate(20deg);
    }
    50% {
        -webkit-transform: rotate(0deg);
    }
    75% {
        -webkit-transform: rotate(-20deg);
    }
    100% {
        -webkit-transform: rotate(0deg);
    }    
}

Demo for Sample 2

Upvotes: 2

Related Questions