CSS 函数 perspective() 用于 3D 转换的上下文。它用于定义元素的透视深度,从而创建可以进行转换的 3D 空间。它采用单个值作为参数,该参数表示观看者与 z=0 平面的距离。结果是 <transform-function> 数据类型。
CSS 函数 perspective() 是应用于要被转换的元素的转换值的一部分。perspective() 函数与属性 perspective 和 perspective-origin 之间的区别在于,后两者与在三维空间中转换的子元素的父元素有关。
可能的值
perspective() 函数采用单个参数,该参数可以是以下参数之一:
- d:是一个 <length> 值,表示用户与 z=0 平面之间的距离。当 d 的值为 0 或负数时,不会对元素应用透视变换。
- none:未在元素上设置任何透视。
语法
perspective(d)
- 将 <length> 值或 none 传递给函数。
- z=0 是所有内容在二维视图中出现的空间。
- 负值被视为无效值,并且是语法错误。
- 小于或等于零的值被限制为 1px。
- 除 none 以外的任何值都会导致 z 轴位置为正值的元素看起来更大,而 z 位置为负值的元素会显得更小。
- z 位置等于或大于透视值的元素将消失。
- 当 perspective() 拥有较大的值时,转换很小,反之亦然。
- Perspective(None) 指定来自无限距离的透视,因此不应用任何转换。
CSS perspective() - 基本示例
以下示例演示了 perspective() 函数的使用,该函数显示了参数 d 的各种值:
<html>
<head>
<style>
.face {
position: absolute;
width: 100px;
height: 100px;
line-height: 100px;
font-size: 100px;
text-align: center;
}
p + div {
width: 100px;
height: 100px;
transform-style: preserve-3d;
margin-left: 100px;
padding: 25px;
}
.without-perspective {
transform: rotateX(-15deg) rotateY(30deg);
}
.with-perspective-none {
transform: perspective(none) rotateX(-15deg) rotateY(30deg);
}
.with-perspective-larger {
transform: perspective(8cm) rotateX(-15deg) rotateY(30deg);
}
.with-perspective-smaller {
transform: perspective(3.1cm) rotateX(-15deg) rotateY(30deg);
}
.top {
background-color:lightyellow;
transform: rotateX(90deg) translate3d(0, 0, 50px);
}
.left {
background-color:teal;
transform: rotateY(-90deg) translate3d(0, 0, 50px);
}
.front {
background-color: cadetblue;
transform: translate3d(0, 0, 50px);
}
</style>
</head>
<body>
<p>Without perspective:</p>
<div class="without-perspective">
<div class="face front">1</div>
<div class="face top">2</div>
<div class="face left">3</div>
</div>
<p>With perspective (none):</p>
<div class="with-perspective-none">
<div class="face front">1</div>
<div class="face top">2</div>
<div class="face left">3</div>
</div>
<p>With perspective (8cm):</p>
<div class="with-perspective-larger">
<div class="face front">1</div>
<div class="face top">2</div>
<div class="face left">3</div>
</div>
<p>With perspective (3.1cm):</p>
<div class="with-perspective-smaller">
<div class="face front">1</div>
<div class="face top">2</div>
<div class="face left">3</div>
</div>
</body>
</html>