One of the main reasons the emergence of CSS3 has been so hotly anticipated is the fact that, in combination with HTML5, it will pose a genuine alternative to technologies such as Flash. With CSS3 and HTML5, you will ultimately be able to create animated, interactive multimedia applications that will be accessible to users regardless of whether Flash is supported in their environment – great news if you’re developing Web apps for iOS or for mobile users in general. In this tutorial we will create a simple first animation using CSS3 keyframes.
Our animation is going to feature a childish cartoon bus moving along the X axis, speeding up in the middle before slowing down again. The bus and wheels will be separate images, with the wheels spinning as the bus moves. These are our image files:
Here is a screenshot from the final animation:
Create a Web Page
Let’s create an HTML5 page as follows:
<!DOCTYPE html> <html> <head> <style type="text/css"> </style> </head> <body> </body> </html>Add the image elements to the body section of your page, including the bus and two copies of the wheel:
<div> <img class="bus" src="bus.png"/> <img class="b_wheel" src="wheel.png"/> <img class="f_wheel" src="wheel.png"/> </div>We will use the class attributes to apply styling to the image elements.
Apply Default Styling
Start your CSS3 code by adding style properties for the container “div” as follows:
/*background element*/ div { width:600px; height:220px; background: linear-gradient(top, blue, green); background: -moz-linear-gradient(top, blue, green); background: -webkit-linear-gradient(top, blue, green); }Here we simply apply a gradient background together with dimensions. Notice that the prefixes we are using only include the default syntax plus versions for Mozilla and Webkit (Safari and Chrome). Internet Explorer and Opera do not yet support the techniques we will be using in this tutorial so we will not be targeting them.
Now add properties for the initial style of your wheel images:
/*initial properties*/ .f_wheel { position:absolute; top:160px; left:190px; } .b_wheel { position:absolute; top:160px; left:50px; }We use absolute positioning to make sure the wheels and bus are displayed correctly and will move together. Add the initial styling for the bus image:
/*bus properties*/ .bus { position:absolute; top:50px; left:30px; /*animations*/ }We are going to add more properties in this block, indicating the animations we want to apply to the bus element.
Indicate the Animations
Our bus moving and wheel spinning animations are going to be specified using CSS3 keyframes. We will define the animations in dedicated keyframes sections, but we also need to tell the browser to apply these animations to particular elements. Add the following to your existing “.bus” declarations:
animation: moveBus 5s ease-in-out forwards;...