preface
Today I would like to share with my friends how to use CSS to achieve a cube. This article covers some of the less commonly used CSS properties: Perspective, Perspective-Origin, and transform-style.
- Perspective: Specifies the distance between the observer and the z=0 plane, creating perspective for elements with 3d position transitions. Three dimensional elements with z>0 are larger than normal, while those with z<0 are smaller than normal.
- Perspective-origin: Specifies the position of the observer, which is used as the vanishing point for the Perspective property.
- Transform-style: Sets whether the element’s children reside in 3D space or in a plane.
structure
<div class="container">
<div class="cube">
<div class="back">back</div>
<div class="down">down</div>
<div class="up">up</div>
<div class="right">right</div>
<div class="left">left</div>
<div class="front">front</div>
</div>
</div>
Copy the code
The method I adopted was to use positioning to overlap the six faces of the cube. You can also design the DOM structure as one of the 11 cube plans shown below.
style
* {
margin: 0;
padding: 0;
}
.container {
perspective: 800px;
perspective-origin: center -200px;
}
.cube {
position: relative;
width: 150px;
height: 150px;
margin: calc(50vh - 75px) auto;
/* Set child elements in 3D space */
transform-style: preserve-3d;
transform: rotateY(-45deg);
}
/* Overlap */
.cube div {
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
line-height: 150px;
text-align: center;
font-size: 30px;
color: #FFF;
}
.front {
background: rgba(255.0.0.0.5);
animation: front .5s ease .5s forwards;
}
.left {
background: rgba(255.251.0.0.5);
animation: left .5s ease 1.5s forwards;
}
.right {
background: rgba(72.255.0.0.5);
animation: right .5s ease 2s forwards;
}
.up {
background: rgba(0.195.255.0.5);
animation: up .5s ease 2.5s forwards;
}
.down {
background: rgba(255.0.221.0.5);
animation: down .5s ease 3s forwards;
}
.back {
background: rgba(255.0.221.0.5);
animation: back .5s ease 1s forwards;
}
/* Break down animation */
@keyframes front {
0% {
transform: translateZ(0);
}
100% {
transform: translateZ(75px);
}
}
@keyframes left {
0% {
transform: translateX(0) rotateY(0);
}
100% {
transform: translateX(-75px) rotateY(-90deg);
}
}
@keyframes right {
0% {
transform: translateX(0) rotateY(0);
}
100% {
transform: translateX(75px) rotateY(90deg);
}
}
@keyframes up {
0% {
transform: translateY(0) rotateX(0);
}
100% {
transform: translateY(-75px) rotateX(90deg);
}
}
@keyframes down {
0% {
transform: translateY(0) rotateX(0);
}
100% {
transform: translateY(75px) rotateX(-90deg);
}
}
@keyframes back {
0% {
transform: translateZ(0);
}
100% {
transform: translateZ(-75px); }}Copy the code
Demo: jsdemo. Codeman. Top/HTML/cube. H…