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.)
If you want it to be done in CSS, this is the way:
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)
From the answers given thus far I take it that there is no simpler approach than using JavaScript to "realign" the image. Let me therefore share the approach which I ended up using:
myrotate
is theid
of the<a>
which I abuse as switch,myimage
is (guess) theid
of theimg
to rotate.Try it here.
Using some jQuery, you can get the
offset
of the parent, subtract that from the new rotatedoffset
and use margin to put it back to the container. It works with all rotations. Here is the Fiddle.JS:
I take the @Lost Left Stack example and changed it to work with all rotations, and be repetitive. Resets margins for repetitive rotations. Also set right and bottom margins.
example: http://jsfiddle.net/v4qa0x5g/2/
I don't know if there is a simplier way, but you can set margin of the image after rotation like this.
You can use js to get image width and height so it sets values accordingly to the size of image. I used manual way.
http://jsfiddle.net/YQktn/3/
EDIT:
You can always mess with
as found here: CSS "transform: rotate()" affecting overall design with "position: absolute" (not aligning properly)