css transform rotation and parent element dimensions

When you use css3 to rotate an element with it’s new transform property, you may find yourself fighting to keep it inside it’s parent.

To clarify, usually rotating an element will first put it into it’s usual position and then literally rotate it around it’s own centre, not caring if it now overlaps elements around it (well I suppose that’s the point sometimes?!?)

I’m using css transform to rotate, in combination with a little javascript to allow images to be rotated (and then saved) as part of PagePlay‘s super simple user interface.

So what I wanted was for the parent div to sit around the image. The problem here is that the div parent doesn’t (and shouldn’t) care about the rotation of it’s child, so we need to make the div larger when it’s rotated. To do this I used a little bit of jQuery and maths to calculate the required additional space…

I don’t know whether the image is going to be taller or wider first, so we need to check that first and come up with a pixel margin to use later…

The img width minus image height divided by 2 is the amount space above and below the standard space the image takes up that it will also need when rotated. If the image is taller than it is wide, we will already have enough space (you could do better by making the div smaller on rotation in this case).

So when we rotate we look at whether the image is rotated or not (rev tells me that here) and then based on that we add or remove the margin we calculated above to the top and bottom of the image to push it’s parent div away from it and make it large enough to accommodate the image.

img.css({marginTop:(rev ? 0 : marg),marginBottom:(rev ? 0 : marg)});

You could certainly do better with dealing with image which are portrait, but then maybe I’ll come back to that another time.