TLDR; a simple CSS trick using a square <div> to make irregularly shaped images spin in a perfect circle
One of the ways I push myself to evolve as a web developer is to take a website design and imagine how it ought to be. I always ask myself what I would like to see in it. Once I have an answer for that, the next question is what I can do to realize it. I’ll show you what I mean.
Do you see what I see when looking at this title? The text “It’s all about” forms an arc of a circle. Call it connecting the dots or filling in the blank, when I see an arc, I want to make a circle out of it.
To transform and rotate
That was the first method I tried in my attempt to make this curvy body of text rotate in a circle. The result was disorienting. The reason for that is because the png file that contains the image of the text has 207-by-123 pixel dimensions. It’s a rectangle, and I was rotating the image from its centre point, which does not coincide with the centre of the circle around which the text is curved as the next diagram shows.
Axis of rotation
Technically, this problem can be solved by using the CSS property ‘transform: origin’. As its name suggests, this property allows us to move the axis of rotation from the centre of the rectangle to that of the circle in the previous diagram. There are, however, two major issues with this approach. Firstly, it takes a lot of fine tuning to get the rotation axis to be close enough to the centre of the circle, so as not to cause any distraction in the animation. Secondly, an application of ‘transform: scale’ on the image will throw off this fine tuning, and we have to start searching for the centre of the circle again.
The problem would be much simpler if we were dealing with a square image rather than a rectangular one.
When a square is not around …
… we construct a <div> and make it right, of course. After some staring at screens that was my solution. Make a <div> container for png image. Fine tune its width (and height) till you get a perfect circular rotation of the text. Yes, there is still some fine tuning to do, but now we only need to change one value since the width and height of the square are the same, whereas with ‘transform: origin’ we would have to fine tune 2 values which correspond to the x and y axes of the screen.
The second advantage of having a square container for the image is, we can rotate the container and the image will rotate with it. Scale the container up (or down) and the image will follow without upsetting the alignment between the rotation axis and the centre of the circle.
And so round and round it goes.