No.5 - 纯 CSS 制作绕中轴旋转的立方体

时间:2024-06-03 08:34:38
body{
background-color: #000;
margin:;
padding:;
}
main{
perspective: 800px;
}
.cube{
transform-style: preserve-3d;
position: relative;
margin: 200px auto 0px;
width: 400px;
height: 400px;
animation: spin 8s linear infinite;
animation-play-state: paused;
}
.cube>div{
background-color: blue;
opacity: 0.3;
position: absolute;
outline: 3px solid #0af;
width: 400px;
height:400px;
}
.cube>div:nth-child(1){
transform: translateZ(200px);
}
.cube>div:nth-child(2){
transform: rotateY(180deg) translateZ(200px);
}
.cube>div:nth-child(3){
transform: rotateY(90deg) translateZ(200px);
}
.cube>div:nth-child(4){
transform: rotateY(-90deg) translateZ(200px);
}
.cube>div:nth-child(5){
transform: rotateX(90deg) translateZ(200px);
}
.cube>div:nth-child(6){
transform: rotateX(-90deg) translateZ(200px);
}
@keyframes spin{
100%{transform: rotateY(-360deg);}
}
.cube:hover{
animation-play-state: running;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>纯 CSS 制作绕中轴旋转的立方体</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<div class="cube">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</main>
</body>
</html>

划重点

①给多个元素absolute形成重叠

②transform: rotateY(180deg) translateZ(200px);和transform: translateZ(200px)  rotateY(180deg);

先后的不同,有巨大区别!

.cube>div:nth-child(1){
transform: translateZ(200px);
}
.cube>div:nth-child(2){
transform: rotateY(180deg) translateZ(200px);
}
.cube>div:nth-child(3){
transform: rotateY(90deg) translateZ(200px);
}
.cube>div:nth-child(4){
transform: rotateY(-90deg) translateZ(200px);
}
.cube>div:nth-child(5){
transform: rotateX(90deg) translateZ(200px);
}
.cube>div:nth-child(6){
transform: rotateX(-90deg) translateZ(200px);
}

先在中点进行旋转,随后分别向各自变化后的Z方向推进200px;

而不是集体推进200px后在中点进行旋转。

③margin:200px auto 0px;

④3D舞台元素对视角的作用决定性(一个类似body的大背景座位舞台元素起到对屏幕更真实的效果)

animation: name duration timing-function delay iteration-count direction;
animation-play-state: paused;
animation-play-state: running;
@keyframes myfirst
{
0% {background: red; left:0px; top:0px;}
25% {background: yellow; left:200px; top:0px;}
50% {background: blue; left:200px; top:200px;}
75% {background: green; left:0px; top:200px;}
100% {background: red; left:0px; top:0px;}
}
.cube:hover{
animation-play-state: running;
}