Here we will demonstrate how to rotate an image using HTML and CSS only. This method can also be applied to rotate an image by any value from 0-360 degrees and for this example I’ll be using 15 degrees. I’ve tested it as working in Internet Explorer 6, 7, 8 and 9, Firefox 3.6 and 7, Windows Safari and Google Chrome.
Note: For simplicity’s sake, in this example the image is ONLY rotated (i.e. NOT scaled, shifted etc.)
Here is the rotated image:
Image rotation HTML code
<img src="html-css-tips-tricks/img/beluga_close.jpg" />
Image rotation CSS code
filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand',
The ‘-moz-transform’ and ‘-webkit-transform’ styles are straighforward. The ‘filter’ style is not so much straighforward, so I have included some explanation below.
Image rotation notes for ‘filter’ CSS
I used this for reference: Wikipedia – Transformation matrix.
DON’T PANIC! The maths for this is not as complicated as it first seems and all you need is your PC’s Calculator (found under Start >> All Programs >> Accessories >> Calculator) in Windows XP. It also needs to be set to ‘Scientific’ using the ‘View’ menu.
Use the calculator to work out the following values, replacing the ‘x’ with the number of degrees you want to rotate your image:
M11 = cos(x)
M12 = -sin(x)
M21 = sin(x)
M22 = cos(x)
In the above example I rounded the above values off to 10 decimal places, which still gives excellent precision.
Rotating an image by 90, 180 or 270 degrees
If you want to rotate an image by 90, 180 or 270 degrees, it’s easier to use the Microsoft “BasicImage” filter for Internet Explorer. The ‘rotation’ parameter values 0, 1, 2 and 3 correspond to 0, 90, 180 and 270 degrees respectfully. So to rotate an image by 90 degrees, the CSS is: