Hostgator coupons for up to 99% off hosting for Dynamic Drive visitors!
Advanced Search Usage Terms Submit Contact
Dynamic Drive CSS Library

CSS Library: CSS3 demos: Here

Swinging keyframe animation

Author: Dynamic Drive

Using CSS3 keyframe animations, we can control the exact style of an element at any point in time. Here we use keyframes to create a swinging effect, by modifying an element's rotation gradually over time until resting position, or 0 degrees.

Demo (requires IE10+, FF, Chrome, Safari etc):

Images swings every 5 seconds or so.

The animation is defined using the animation property:

animation: swinging 10s ease-in-out 0s infinite;

This creates an animation that runs 10 seconds on each iteration, cycling perpetually (the 0s defines the default pause before the very first animation is run).

The actual swinging effect is defined using CSS keyframes, specifically:

@keyframes swinging{
0% { transform: rotate(0); }
5% { transform: rotate(10deg); }
10% { transform: rotate(-9deg); }
15% { transform: rotate(8deg); }
20% { transform: rotate(-7deg); }
25% { transform: rotate(6deg); }
30% { transform: rotate(-5deg); }
35% { transform: rotate(4deg); }
40% { transform: rotate(-3deg); }
45% { transform: rotate(2deg); }
50% { transform: rotate(0); } /* Come to rest at 50%. The rest is just stillness */
100% { transform: rotate(0); }

Now, you will have noticed that there is a pause between each swinging effect; in other words, each element isn't swinging all the time. This is achieved by prematurely animating all of the styles, in this case, at the 50% mark, and essentially idling the animation afterwards. This creates the illusion of the animation pausing. A little math tells us then that the visible swing animation lasts for 5 seconds (10s * 0.5) each time, and the pause, also for 5 seconds. You can adjust this ratio to your liking.

The CSS:


Code Info

Rate this code:

Date Posted: 04/26/2013

Revision History: None

Usage Terms: Click here

Your Comments
Copyright 2006-2016 Dynamic Drive