CSS Property perspective








The perspective CSS property adds a 3D feel to element.

The smaller the value, the closer you get from the Z order. The greater the value, the more subtle will be the effect.

It is the child elements that get the perspective view, not the element itself.

Summary

Initial value
none
Inherited
no
CSS Version
CSS3
JavaScript syntax
object.style.perspective="50px"
Animatable
yes

CSS Syntax

perspective: length|none;

Property Values

length
How far the element is placed from the user
none
Default value. Same as 0. The perspective is not set

Browser compatibility

perspective 36.0 (12.0 -webkit-) 10.0 Yes Yes Yes




Example

<!DOCTYPE html>
<html>
<head>
<style>
#div1 {<!--from www. ja v  a2 s .  c  o m-->
    position: relative;
    height: 150px;
    width: 150px;
    margin: 50px;
    padding: 10px;
    -webkit-perspective: 150px; /* Chrome, Safari, Opera  */
    perspective: 150px;
}

#div2 {
    padding: 50px;
    position: absolute;
    border: 1px solid black;
    background-color: red;
    -webkit-transform: rotateX(45deg); /* Chrome, Safari, Opera  */
    transform: rotateX(45deg);
}
</style>
</head>
<body>

<div id="div1">
  <div id="div2">HELLO</div>
</div>
 
</body>
</html>

Click to view the demo





Example 2

The following code creates 3D cube.

<!DOCTYPE html>
<html>
<style>
.wrapper {<!--  www .jav a 2 s  .c om-->
  width: 50%;
  float: left;
}

.w1 {
  perspective: 1000px;
}

.w2 {
  perspective: 2500px;
}

.wrapper h1 {
  text-align: center;
}

.cube {
  font-size: 4em;
  width: 2em;
  margin: 1.5em auto;
  transform-style: preserve-3d;
  transform: rotateX(-40deg) rotateY(32deg);
}

.side {
  position: absolute;
  width: 2em;
  height: 2em;
  background: rgba(255, 0, 0, 0.6);
  border: 1px solid black;
  color: white;
  text-align: center;
  line-height: 2em;
}

.front {
  transform: translateZ(1em);
}

.top {
  transform: rotateX(90deg) translateZ(1em);
}

.right {
  transform: rotateY(90deg) translateZ(1em);
}

.left {
  transform: rotateY(-90deg) translateZ(1em);
}

.bottom {
  transform: rotateX(-90deg) translateZ(1em);
}

.back {
  transform: rotateY(-180deg) translateZ(1em);
}
</style></head><body>
<div class="wrapper w1">
  <div class="cube">
    <div class="side  front">1</div>
    <div class="side   back">6</div>
    <div class="side  right">4</div>
    <div class="side   left">3</div>
    <div class="side    top">5</div>
    <div class="side bottom">2</div>
  </div>
</div>
<div class="wrapper w2">
  <div class="cube">
    <div class="side  front">1</div>
    <div class="side   back">6</div>
    <div class="side  right">4</div>
    <div class="side   left">3</div>
    <div class="side    top">5</div>
    <div class="side bottom">2</div>
  </div>
</div>
</body>
</html>

Click to view the demo