A Trick: Individual CSS Transform Functions

We get a lot of power through the single transform property in CSS – allowing us to rotate, translate, scale, and more all at once. But allowing all of those different transform functions into one property can trip us up.

It’s common to want to apply different transforms to different states of our elements. Say we have a button that we always want to be translated -150% vertically. When a user hovers over the button we scale the button down a bit, and on press (the active state) we rotate it 180 degrees. This example shows how one might first think to write the CSS for “My Button” as just described, and then the “Expected” button shows a way to get it as intended.

With the initial styles on the button we are not just adding the scale on hover… we are overriding the original translate as well, so it scales and transitions back to translateY(0).

Why is this? Linear Algebra. The way these transformations happen depend on each other and their order (such that translate(-50%, -50%) scale(.4) rotate(50deg) is different than rotate(50deg) translate(-50%, -50%) scale(.4)), and they boil down to matrix multiplication. But we usually don’t need to know transforms at that level. Web developers just want to know how they can maintain these transform functions at an individual level.

Read Full Article

Leave a Reply

Your email address will not be published.