怎样利用css画一个正方体呢?
话不多说,直接上代码:
首先是html结构:

1
2
3
4
5
6
7
8
9
10
<div class="app">
<div class="box">
<div class="inner top">1</div>
<div class="inner bottom">2</div>
<div class="inner left">3</div>
<div class="inner right">4</div>
<div class="inner front">5</div>
<div class="inner back">6</div>
</div>
</div>

然后是样式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
.box {
width: 300px;
height: 300px;
position: relative;
transform-style: preserve-3d;
animation: move 5s linear infinite;
}
.inner {
position: absolute;
text-align: center;
font-size: 100px;
color: #fff;
line-height: 400px;
width: 400px;
height: 400px;
border: 1px solid hotpink;
background-color: rgba(155,150,26,.6);
}
.top {
transform: rotateX(90deg) translateZ(200px);
}
.bottom {
transform: rotateX(90deg) translateZ(-200px);
}
.front {
transform: translateZ(200px);
}
.back {
transform: translateZ(-200px);
}
.left {
transform: rotateY(-90deg) translateZ(200px);
}
.right {
transform: rotateY(90deg) translateZ(200px);
}

到这里还没完,目前的效果是叠在一起的,还需要加一个视角。

1
2
3
4
.app {
margin: 200px 500px;
perspective: 2400px;
}

在最外层元素app的盒子上加perspective属性,perspective的意义在于设置远近点大小的比例,让它产生3D感,但是并不改变物体在transform-origin处的大小。
为了能看得更加清楚全面,我们给盒子加个动画,所以最终代码为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
.app {
margin: 200px 500px;
perspective: 2400px;
}
.box {
width: 300px;
height: 300px;
position: relative;
transform-style: preserve-3d;
animation: move 5s linear infinite;
}
.inner {
position: absolute;
text-align: center;
font-size: 100px;
color: #fff;
line-height: 400px;
width: 400px;
height: 400px;
border: 1px solid hotpink;
background-color: rgba(155,150,26,.6);
}
.top {
transform: rotateX(90deg) translateZ(200px);
}
.bottom {
transform: rotateX(90deg) translateZ(-200px);
}
.front {
transform: translateZ(200px);
}
.back {
transform: translateZ(-200px);
}
.left {
transform: rotateY(-90deg) translateZ(200px);
}
.right {
transform: rotateY(90deg) translateZ(200px);
}
@keyframes move {
0% {
transform: rotateY(0) rotateX(0);
}
100% {
transform: rotateY(360deg) rotateX(360deg);
}
}