12 February 2010

Recently I have been strolling around the web looking at CSS3 animations and have been blown away by what people have been doing with it. So I decided I ought to give it a go and see what it’s like to work with. It turns out its dead easy despite the ever present vendor prefixes.

I started off with this markup:

<div id="imageViewer">
   <div id="imageViewerImages">
      <img src="./images/image1.png" alt="flower" />
      <img src="./images/image2.png" alt="flower1"/>
      <img src="./images/image3.png" alt="flower2"/>
      <img src="./images/image4.png" alt="flower3" />
      <img src="./images/image5.png" alt="flower4"/>

<div id="imageViewerControls"></div>

So thats just a div within a div filled with a set of images and a placeholder div for some controls to move between photos. Now we need to style it and add the magic CSS that will animate our css properties when they change.

Below is the CSS I used:

#imageViewer {

#imageViewerImages {
	-webkit-transition:all 1.0s ease-in-out;
	-moz-transition:all 1.0s ease-in-out;
	-o-transition:all 1.0s ease-in-out;
	-transition:all 1.0s ease-in-out;

#imageViewerImages img {

#imageViewerControls div {

#imageViewerControls {

What we have here is #imageViewer the container div which shows a 320x214 pixel window with its overflow hidden so you only see one photo. #ImageVieweImages holds all the images. It also hold the transition tag. This is the part which handles all the animation.

The transision tag is made up of 3 parts:

transition:\[all\] \[1.0s\] \[ease-in-out\];

The first part is what css properties it applies to with \[all\] meaning any property on that item. The second part \[1.0s\] is how long the animation should last and the third part is the type of animation. The type of animation adjusts the speed of animating through the time. The \[ease-in-out\] attribute for example starts slowly, speeds up and then slows down again towards the end.

Now all we need to do is add some controls to change the current image. For this we are going to write a tiny bit of JavaScript to alter the left property of the div thats holding all the images. Below is the script.

<script type="text/javascript">

$(document).ready(function() {
	$("#imageViewerImages img").each(function(i) {
		$("#imageViewerControls").append($("<div/>").html(this.alt).click(function() {
			var left = ((i * 320) * -1).toString() + "px";



What the script is doing is grabbing each of the images in the carousel, getting its alt text and appending a div to the controls div with a click event. The click event then works out how far right the image needs to be pushed to show completely and then sets the left value with the css transition handling all the animation for you.

That’s it. If its all gone to plan you should see something like what I have below.

blog comments powered by Disqus