CSS: rotate image and align top left

fuenfundachtzig picture fuenfundachtzig · Aug 30, 2013 · Viewed 18.7k times · Source

I am trying to rotate an image using a CSS transform such that it stays correctly aligned within the surrounding div, i.e. the top left corner of the image should be aligned with the top left corner of the div.

As you can see here (-> click on [rotate]) this does not work. Is there a way to fix this?

(Note that I'd be using this in an online image viewer so I cannot hardcode an offset for the rotated image. There's a lot of similar questions but I haven't found this exact question.)

Answer

vals picture vals · Aug 30, 2013

If you want it to be done in CSS, this is the way:

.rot90 {
    -webkit-transform: translateY(-100%) rotate(90deg); /* Safari */
    -moz-transform: translateY(-100%) rotate(90deg); /* Firefox 3.6 Firefox 4 */
    /*-moz-transform-origin: right top; */
    -ms-transform: translateY(-100%) rotate(90deg); /* IE9 */
    -o-transform: translateY(-100%) rotate(90deg); /* Opera */
    transform: translateY(-100%) rotate(90deg); /* W3C */  
    -webkit-transform-origin: left bottom;
    -moz-transform-origin: left bottom;
    -ms-transform-origin: left bottom;
    -o-transform-origin: left bottom;
    transform-origin: left bottom;
}

updated demo

The trick is to rotate the image around the left bottom corner. Once done, it is down by 100% of the height; translate it and now it is ok.

To get the same effect for the inverse rotation: (hover to transform)

div:hover #myimage {
    -webkit-transform: translateX(-100%) rotate(-90deg); /* Safari */
    -moz-transform: translateX(-100%) rotate(-90deg); /* Firefox 3.6 Firefox 4 */
    -ms-transform: translateX(-100%) rotate(-90deg); /* IE9 */
    -o-transform: translateX(-100%) rotate(-90deg); /* Opera */
    transform: translateX(-100%) rotate(-90deg); /* W3C */  
    -webkit-transform-origin: top right;
    -moz-transform-origin: top right;
    -ms-transform-origin: top right;
    -o-transform-origin: top right;
    transform-origin: top right;
}
<div style="border: 1px solid red;">
  <img id="myimage" src="http://upload.wikimedia.org/wikipedia/mediawiki/a/a9/Example.jpg" style="border: 3px solid silver;" />
</div>