CSS AdvancedLesson #135

3D Perspective

To activate a 3D space, the element needs perspective. The perspective defines the distance between the user's viewpoint and the

CSS Perspective

To activate a 3D space, the element needs perspective. The perspective defines the distance between the user's viewpoint and the object.

A low value, like perspective: 200px;, assumes that the user is close to the object and creates a strong 3D effect.

A high value, like perspective: 2000px;, assumes that the user is far away from the object and creates a mild 3D effect.

Without perspective, any 3D transforms will look flat and two-dimensional.

A perspective can be added in two ways:

  • With the perspective property
  • With the perspective() function

Using the perspective Property

The perspective property is always set on the parent element, and each child will share the same 3D space.

Example

Example Code

css
Try it Yourself
.container {
  width: 180px;
  height: 180px;
  border:
  1px solid lightgray;
  margin: 30px;
  perspective: 500px; /*
  set perspective on parent element */

  }

.box {
  width:
  100%;
  height: 100%;
  background-color: green;

  transform: rotateY(45deg);
}

Using the perspective() Function

The perspective() function is used to directly apply a 3D transform to a single element:

Example

Example Code

css
Try it Yourself
.container {
  width: 180px;
  height: 180px;
  border:
  1px solid lightgray;
  margin: 30px;
}

.box {
  width:
  100%;
  height: 100%;
  background-color: green;

  /* perspective function in transform property */

  transform: perspective(500px) rotateY(45deg);
}

Both of the examples above produce the same result.

However: When you put the perspective property on a parent element, each child will share the same 3D space, while the perspective() function is used to directly apply a 3D transform to one single element.

Interactive Code Examples

CSS Example 1

css
Try it Yourself
Interactive runnable CSS example from EA Academy.
Live Output Preview:

CSS Example 2

css
Try it Yourself
Interactive runnable CSS example from EA Academy.
Live Output Preview: