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.)
css file, stylesheet, or <style> tags, you can use the CSS class name in any of your image tags. To rotate an image by another measure of degrees, change the "180" in the CSS code and <img> tag to the degree you desire.
We can add the following to a particular tag in CSS: -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -o-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); In case of half rotation change 90 to 45 .
The CSS rotate() function lets you rotate an element on a 2D axis. The rotate() function accepts one argument: the angle at which you want to rotate your web element. You can rotate an element clockwise or counter-clockwise.
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;
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With