Writing 3D transforms that work correctly on web pages requires use of perspective
, and it is the application of this property that most developers struggle with when approaching CSS 3D for the first time.
First and most importantly, perspective
is typically set on outer container elements such as <body>
, <figure>
and <div>
. Doing so allows the 3D manipulation of child elements, such as images, that exist inside the container. You can think of perspective
as being similar to flexbox, in that the property influences the appearance of elements inside tags to which it is applied. Applying 3D transforms to elements that do not inherit perspective
from their parents will not deliver expected or logical results.
perspective
requires a value. (In Webkit browsers, the property also requires a vendor prefix, but we will ignore that for the sake of clarity until the final example).
In my book, Pro CSS3 Animation, I compare the value of
perspective
to the focal length of a lens on an SLR camera, a metaphor that I will extend here:
Perspective value (pixels) | Description |
---|---|
0 | No perspective applied to child elements; the majority of 3D transforms will not work as expected |
1 – 200 | Akin to a “fisheye” lens*: most 3D transforms will be grossly distorted. |
200 – 700 | Moderate lens: effects will appear in scale. |
700+ | Telephoto lens**: most 3D effects will appear “flattened”. |
Note that the values above are approximate: the exact integer and unit of measurement you apply to perspective
will depend on a number of factors, including the relative size of the container and child elements.
You can see an example of altered perspective values in the interactive tool at the top of this article. Try manipulating the slider: while the image's rotation is kept constant, manipulating the perspective
value of its container element creates very different visual effects.
Applying Perspective
You can associate perspective
through that property name, or transform-perspective
: either works, but I prefer using the former for brevity.
div#container {
perspective: 700px;
}
Conclusion
This article introduced the basics of perspective
; the next entry will discuss advanced uses and potential traps of the property, together with the use of perspective-origin
.
*Practically, the focal length of most SLR fisheye lenses tops out at around 18mm
** Again, real SLR telephoto lenses start at lower values: typically around 180mm
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/NPjwWw