Variable CSS Perspectives and Transform-Functions

When working with 3D animations with CSS, one thing that is rarely mentioned is that CSS3’s perspective property is largely linked to the element height. This is likely because it normally wouldn’t be an issue. Applying perspective to an element wrapping a transformed element or group of transformed elements forces the elements to behave similarly and all ‘start’ from the same spot.

Where we run into trouble, however, is when we want the transformation perspective to be the same across various pages or when elements can have variable or unknown heights and aren’t wrapped in a similar container.

For example, if I wanted a Y-rotation of 10 degrees to look the same across three different elements with unknown heights, it would look something like this:

[codepen_embed height=”268″ theme_id=”0″ slug_hash=”Dygwd” default_tab=”result”]See the Pen <a href=’http://codepen.io/aicarlson/pen/Dygwd/’>Variable CSS Perspectives — Before</a> by Andrew Carlson (<a href=’http://codepen.io/aicarlson’>@aicarlson</a>) on <a href=’http://codepen.io’>CodePen</a>.[/codepen_embed]

Not great, right? It’s not overly drastic in this case, but they certainly aren’t the same.

The best way I’ve found to combat this problem so far is to calculate the perspective based on the height of the element and then apply it to the element itself using a CSS transform-function.

First find a ratio that you like the look of. So if you like the look of an element with a 10 degree rotation that’s 50px tall and has an inherited perspective of 200px, your ratio would be 4 or 200/50.

After you have your ratio it’s just a few lines of jQuery:

$('.element').css({
  '-webkit-transform': 'perspective(' + $('.element').height() * 4 + 'px) rotateY(10deg)',
  'transform': 'perspective(' + $('.element').height() * 4 + 'px) rotateY(10deg)
});

Which will result in something like:

[codepen_embed height=”268″ theme_id=”0″ slug_hash=”bteDz” default_tab=”result”]See the Pen <a href=’http://codepen.io/aicarlson/pen/bteDz/’>Variable CSS Perspectives — After</a> by Andrew Carlson (<a href=’http://codepen.io/aicarlson’>@aicarlson</a>) on <a href=’http://codepen.io’>CodePen</a>.[/codepen_embed]

One practical application for this is creating a menu that pushes the whole document back into the background when the menu is active. On one page the perspective might be fine and look great, but on another page the document height will likely be different, thus throwing off your perspective and ruining the transformation.

Leave a Reply

Your email address will not be published.