Thursday, June 14, 2012

CSS3 3D Transforms - Function Order Matters!

Previously, we explored the basics of CSS3 3D Transforms. A transform is generated by using one or more of the 3D transform functions, like so: If you're not careful, you'll find that the elements you're trying to manipulate in 3D space don't look like you'd expect. This can happen when you've applied the transform functions in an incorrect order.

Let's say we want to rotate the element by 90 degrees and translate (i.e., move) it down the Y axis by 150 pixels. Depending on the order of the functions, you'll get one of these two results:

Example showing rotation and translation functions in different orders.
  • In the first example, the translation was applied first, followed by the rotation.
  • In the second example, the rotation was applied first and then translation was applied.

So why did the function order affect the result? Because in the second example, the rotation caused the Y axis to change. That is, the Y axis for the translation had been rotated 90 degrees along with the element. In other words, it's not using the global Y axis – it's using the element's Y axis.

Here's another example using scaling + translation.

Example showing scaling and translation functions applied in different orders.
  • In the first example, scale was applied first, and then translation.
  • In the second example, translation was applied first, and then scale.

Notice how in the first case, the scale affected the translation. That is, although we specified a 100px translation, the fact that the element was scaled by 2 caused it to actually move 200px.

All right, one more example – scaling + rotation.

Scaling and rotation functions applied in different orders
  • In the first example, rotationZ was applied before scaleX. The result is that the face looks wide.
  • In the second, scaleX was applied before rotationZ, which caused the face to look tall.

The reason is that in the first case, the X axis had rotated. In the second case, the X axis had not yet rotated when the scaleX was applied.

The Moral of the Story?

If your 3D transform doesn't come out looking like you expected it to, double check the order of the functions!

Related Stuff

No comments:

Post a Comment

Profile Picture
Dave Leeds
My Hobbies:
  • Programming
  • Cartooning
  • Music Writing
Full Profile