Rotating an image by any angle using CSS

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:

Beluga - rotated image

Image rotation HTML code

<div id="ri-image-container">
  <div id="ri-image">
    <img src="html-css-tips-tricks/img/beluga_close.jpg" />

Image rotation CSS code

#ri-image-container {
  height: 120px;
  position: relative;
  width: 200px;

#ri-image {
  background-color: Gray;
  height: 60px;
  left: 10px;
  padding: 10px;
  position: absolute;
  top: 10px;
  width: 80px;
  -moz-transform: rotate(15deg);
  -ms-transform: rotate(15deg);
  -webkit-transform: rotate(15deg);
  filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand',
    M11=0.9659258262, M12=-0.2588190451,
    M21=0.2588190451, M22=0.9659258262);

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.

Have fun!

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:

filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-webkit-transform: rotate(90deg);

1 Comment on Rotating an image by any angle using CSS

1 Trackbacks & Pingbacks

  1. Homepage

Comments are closed.