rotate image with css

v923z picture v923z · Dec 2, 2012 · Viewed 100k times · Source

I would like to rotate an image by 90 degrees with CSS only. I can do the rotation, but then the position of the image is not what it should be. First, it will overlay some other elements in the same div, and second, its vertical dimension will become bigger than the containing div. Here is my code where the two classes are defined.

Is there a way of keeping the image within the section? I can translate and scale the image so that it is within the section, but that works only, if I know the image size beforehand. I would like to have a reliable method that does not depend on the size.

Answer

James Bone picture James Bone · Nov 5, 2014

The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.

.imagetest img {
  transform: rotate(270deg);
  ...
  margin: 10px 0px;
}

The amount will depend on the difference in height x width of the image. You may also need to add display:inline-block; or display:block to get it to recognize the margin parameter.