Wednesday, November 14, 2012

CSS3 3D Transforms: Rotating Around All the Axises

It seems like a natural evolution to add 3D abilities to the browser.  If you're going to perform 2D transforms.  Why not add 3D transforms?  While not fully supported, 3D transforms are fun and when used appropriately, can really enhance the user experience.

I've been avoiding 3D simply because of the lack of support (IE9 and Opera do not support 3D - see this site for the current support matrix).  However, for fun, I decided to try it out and see how it works.  From a UI perspective, the carousel pattern seems to be a good place to use 3D.  As I was looking for examples, I found this site which has an implementation.

As I looked over the code, I noted several things:

  1. The order of the transform is important.  The wrong order will cause elements to align in unexpected places.

  2. The perspective style will affect the look of the 3D effect.  Most likely, setting it on a container and using transform-style: preserve-3d will be desirable.

  3. Using transform-origin can make it a lot easier to rotate elements in 3D space.

In my sandbox, I created a test to tinker with the different 3D styles to see how they worked. The basic setup is to create a wrapper DIV which will have the perspective style set to some value between 200px and 1000px. Each child DIV will then use transform-style: preserve-3d to inherit the perspective. Additionally, the transform-origin is set so all transforms occur relative to the center of the element but behind the element (by default it is -100px behind each element). Once all the elements have a common transform point established, a rotation transform is applied on one of the DIVs on a specific axis. In this example, the "outer" DIV is rotated around the x-axis, the "inner" DIV is rotated around the z-axis, and the "box" DIVs are rotated around the y-axis.

<div class="wrapper">
<div class="outer">
<div class="inner">
<div class="box">One</div>
<div class="box">Two</div>
<div class="box">Three</div>
<div class="box">Four</div>
<div class="box">Five</div>

The result enables rotating all the elements around the established point of origin on the different axises. There are probably different ways to achieve the same result. The carousel example I linked to above translated the elements on the z-axis to position them properly in space. I prefer using the transform-origin style since the browser does the math for me and makes the code much simpler write and maintain.

While probably not something to use extensively, 3D transforms certainly can add some nice transition effects. If its used appropriately, the transitions could degrade well enough that users visiting with browsers that do not support 3D will still be able to access content. This might require some creative coding or even browser support checks. However, over time, the features will become mainstream and enable a whole new dimension to page design.