transform案例
# transform案例
# 结合perspective和transform-style实现两面翻转盒子的效果
代码示例:
<div class="container-trans">
<div class="content-trans">
<div class="front">正面</div>
<div class="back">反面</div>
</div>
</div>
1
2
3
4
5
6
2
3
4
5
6
.container-trans {
perspective: 800px; /*重点:开启3d透视效果*/
}
.content-trans {
margin: 0 auto;
width: 220px;
height: 220px;
line-height: 220px;
font-size: 16px;
text-align: center;
position: relative;
transform-style: preserve-3d; /*重点:开启子元素的3d效果*/
transition: all 1s;
}
.content-trans:hover {
transform: rotateY(180deg);
}
.front,
.back {
position: absolute;
width: 100%;
height: 100%;
}
.front {
background-color: violet;
z-index: 999;
}
.back {
background-color: yellow;
transform: rotateY(180deg); /*重点:将背面展示的盒子先转过去*/
}
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
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
效果:
# 简易版旋转木马
代码示例:
<div class="container-rotate">
<section class="rotate">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
</div>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
.rotate {
position: relative;
width: 300px;
height: 200px;
margin: 150px auto;
transform-style: preserve-3d; /*开启3d透视*/
animation: rotate 10s linear infinite;
background-color: salmon;
}
@keyframes rotate {
0% {
transform: rotateY(0);
}
100% {
transform: rotateY(360deg);
}
}
.rotate:hover {
animation-play-state: paused; /*鼠标放上去时暂停动画*/
}
.rotate div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.rotate div:nth-child(1) {
background-color: red;
transform: translateZ(300px);
}
.rotate div:nth-child(2) {
background-color: orange;
transform: rotateY(60deg) translateZ(300px);
/*注意:一定要先旋转再移位,因为坐标轴也会跟着旋转,也就是旋转后坐标轴已经改变,这样才能实现效果*/
}
.rotate div:nth-child(3) {
background-color: green;
transform: rotateY(120deg) translateZ(300px);
}
.rotate div:nth-child(4) {
background-color: cyan;
transform: rotateY(180deg) translateZ(300px);
}
.rotate div:nth-child(5) {
background-color: blue;
transform: rotateY(240deg) translateZ(300px);
}
.rotate div:nth-child(6) {
background-color: purple;
transform: rotateY(300deg) translateZ(300px);
}
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
在GitHub上编辑 (opens new window)
上次更新: 1/20/2022, 11:27:12 AM