返回
CSS绘制3D旋转立方体
前端
2024-02-16 13:10:15
前言
3D元素在网页设计中越来越受欢迎,因为它可以为网站添加深度和维度。使用CSS绘制3D旋转立方体是一种简单而有效的方法,可以创建引人注目的视觉效果。
最终效果展示
[图片:旋转的3D立方体]
实现思路
呈现一个立方体需要六个面,上下,左右前后,每个面都代表着一个div,这里我们使用伪类元素来设置上下两个元素,因为左右前后四个面都是成90deg,所以我们使用CSS变量来控制立方体的旋转角度。
/* 创建一个立方体的基本结构 */
.cube {
width: 200px;
height: 200px;
margin: 0 auto;
position: relative;
transform-style: preserve-3d;
animation: spin 5s infinite linear;
}
/* 设置立方体的旋转角度 */
@keyframes spin {
from {
transform: rotateX(0deg) rotateY(0deg);
}
to {
transform: rotateX(360deg) rotateY(360deg);
}
}
/* 设置立方体的正面 */
.cube__front {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
}
/* 设置立方体的背面 */
.cube__back {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: blue;
transform: rotateX(180deg);
}
/* 设置立方体的左面 */
.cube__left {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: green;
transform: rotateY(-90deg);
}
/* 设置立方体的右面 */
.cube__right {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: yellow;
transform: rotateY(90deg);
}
/* 设置立方体的上面 */
.cube__top {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: orange;
transform: rotateX(-90deg);
}
/* 设置立方体的下面 */
.cube__bottom {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: purple;
transform: rotateX(90deg);
}
通过以上代码,我们就可以创建一个旋转的3D立方体了。