With CSS3, you can apply animated effects on Web page elements in 3D as well as 2D.
In this tutorial we will go through the basics of rotating in 3 dimensions and will combine these transforms with the scale and translate transforms for more complex results. We will also add a basic level of interaction to animate the effects as the user interacts with the page.
Create a Page with an Image Element
Create a basic page with a CSS section in the head area, as follows:
<!DOCTYPE html> <html> <head> <style type="text/css"> /*CSS here*/ </style> </head> <body> <!--visible elements--> </body> </html>We will use an image to demonstrate the effects. Add the following code to the body section of your page, altering the source attribute to use your own image file:
<img src="picture.jpg" alt="picture" onclick="this.className='transformed'"/>The click listener JavaScript function is purely for demonstration, so that you can see the effect as it happens. In your own pages you will of course need to incorporate the transform effects with any other functionality you have in place.
Style the Page
Add the following CSS code in the style section to apply default styling to your image element:
img { margin:50px; /*general version*/ transition: 2s; /*browser specific versions*/ -moz-transition: 2s; -webkit-transition: 2s; }We apply a margin of 50px to accommodate the image as it rotates, but depending on the size of your own image, you may wish to alter this. When the user clicks the image, the browser will apply the 3D transform. To make this happen gradually so that you can see the effect unfold, we apply these transition properties making it last two seconds.
Notice the prefixes used in addition to the standard transition syntax – you will also see this throughout the transform code. The 3D transforms are not yet supported in Internet Explorer or Opera, so our CSS prefixes only need to accommodate Firefox, Safari and Chrome.
Rotate the Image
You can rotate your image element with a 3D effect by specifying the X, Y or Z axis. To start with, let’s use the X axis by adding the following CSS code:
.transformed { /*General*/ transform:rotateX(180deg); /*Firefox*/ -moz-transform:rotateX(180deg); /*Chrome, Safari*/ -webkit-transform:rotateX(180deg); }Open your page in the browser and click the image to see the 3D effect. To see the rotation working on the Y axis, alter your CSS as follows, rotating the image 300 degrees as a variation:
.transformed { /*General*/ transform:rotateY(300deg); /*Firefox*/ -moz-transform:rotateY(300deg); /*Chrome, Safari*/ -webkit-transform:rotateY(300deg); }To rotate the image 270 degrees on the Z axis, add the following:
.transformed { /*General*/ transform:rotateZ(270deg);...