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:

See the Pen Variable CSS Perspectives — Before by Andrew Carlson (@aicarlson) on CodePen.0

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:

See the Pen Variable CSS Perspectives — After by Andrew Carlson (@aicarlson) on CodePen.0

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.