Tags: , , ,

I used the animation property in CSS for the first time yesterday. Here’s an overview of some of the basics.
NB: I’m only doing these examples for ‘-webkit-’ as it saves a lot of space, meaning they’re only going to display if you are using chrome or safari.

Here’s the css to get a rolling ball:

/*a container to set position: relative;*/
 .animation {
    position: relative;
    width: 100%;
    height: 100px;
}
#ball {
    -webkit-animation:ball 2s ease-out;
/*this triggers '@-webkit-keyframes ball', 2s makes the % values apply to a time of 2 seconds, the 'ease-out' weights them towards the end of the 2 seconds*/
    background: rgba(114, 159, 207, 1);
    left:74%;
    border-radius: 50%;
    position: absolute;
    top:0;
    left:74%;
    /*NB, regardless of where the animation ends the ball would return to this position afterwards*/
    height: 100px;
    width: 100px;
}
#ball p {
    text-align: center;
    line-height: 100px;
}
/*finally the animation itself, works the same way as transitions, we could set the % values to anything and have as many as we want. This extra level of controll is really what diferentiats it from 'transition'*/
 @-webkit-keyframes ball {
    0% {left:0;-webkit-transform:rotate(0deg);}
    50% {left:90%;-webkit-transform:rotate(360deg);}
    100% {left:74%;-webkit-transform:rotate(0deg);}
}

note, we would need a separate version of the keyframes and the animation property with and without “-webkit-” for browser compatability. (the demos will only work in chrome/safari) and the result:

example

This is a simple example, it’ll run once as soon as the page is ready and then stop. This is because the ‘animation:’ call is included as part of the #ball div. Sticking with pure CSS we can attach it to a :hover or some other selector like so:

example

Though as you can probably see this isn’t a very desirable effect. We should at least stick the :hover to a parent to get rid of the flicker:

.animation:hover>#ball3{-webkit-animation:ball3 2s ease-out;}

example

But as i see it 'animation:' is really for longer and more complicated animations and for those to be worthwhile your really looking for some sort of toggleable trigger.
Its worth noting that animations attached to divs run as soon as the page is ready, not when when all images etc. have loaded, this means even an animation that's intended to run as soon as a user visits a page is better controlled with a jQuery .load command, you can just add a class containing the 'animation:' property:

$(window).load(function () {
	$('#ball').addClass('ball-animation');
});

.ball-animation {-webkit-animation:ball 2s ease-out;}

or do the same thing with any other trigger, scrolling to an element, clicking a button etc. I'll try to give some more practical examples soon.