纯CSS实现3D立方体效果
程序员文章站
2022-05-03 08:21:41
...
<style>
.c{
position: fixed;
top: 200px;
left: 200px;
width: 300px;
height: 300px;
transform: perspective(1000px);
transform-style: preserve-3d;
/* border: 5px solid green; */
animation: zhuan 6s linear infinite;
}
@keyframes zhuan{
from{
transform: rotateX(0) rotateY(0);
}
to{
transform: rotateX(360deg) rotateY(360deg)
}
}
.a{
position: absolute;
width: 200px;
height: 200px;
top: 50px;
left: 25px;
background-color: red;
transform: translateZ(100px);
}
.b{
position: absolute;
width: 200px;
height: 200px;
top: 50px;
left: 25px;
background-color: green;
transform: translateX(100px) rotateY(90deg);
}
.d{
position: absolute;
width: 200px;
height: 200px;
top: 50px;
left: 25px;
background-color: black;
transform: translateX(-100px) rotateY(90deg);
}
.e{
position: absolute;
width: 200px;
height: 200px;
top: 50px;
left: 25px;
background-color: purple;
transform: translateZ(-100px);
}
.f{
position: absolute;
width: 200px;
height: 200px;
top: 50px;
left: 25px;
background-color: gray;
transform: translateY(-100px) rotateX(90deg);
}
.g{
position: absolute;
width: 200px;
height: 200px;
top: 50px;
left: 25px;
background-color: yellow;
transform: translateY(100px) rotateX(90deg);
}
</style>
<div class="c">
<div class="a">正面</div>
<div class="b">右面</div>
<div class="d">左面</div>
<div class="e">背面</div>
<div class="f">顶面</div>
<div class="g">底面</div>
</div>
注意:要实现3D效果首先必须设置transform-style: preserve-3d
;并且设置视距,视距就和在笔直的公路上看一辆远处的车一样,车子越近看到的就越大,车越远看到越小。同理视距越远目标就越小,视距越近目标越大。在父元素设置完3D视距之后
剩余的就是对子元素的合并达到3D立方体的效果。