<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rotating Cube</title>
<style>
body {
background-color: #333;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
perspective: 1000px; /* Add perspective for 3D effect */
}
.cube-container {
width: 200px;
height: 200px;
position: relative;
transform-style: preserve-3d; /* Essential for 3D transforms */
animation: rotate 10s linear infinite; /* Animate the rotation */
}
.cube-face {
position: absolute;
width: 100%;
height: 100%;
opacity: 0.8; /* Make faces slightly transparent */
border: 2px solid white; /* Add borders to the faces */
}
.front {
background-color: rgba(255, 0, 0, 0.5); /* Red */
transform: translateZ(100px);
}
.back {
background-color: rgba(0, 255, 0, 0.5); /* Green */
transform: translateZ(-100px) rotateY(180deg);
}
.right {
background-color: rgba(0, 0, 255, 0.5); /* Blue */
transform: rotateY(90deg) translateZ(100px);
}
.left {
background-color: rgba(255, 255, 0, 0.5); /* Yellow */
transform: rotateY(-90deg) translateZ(100px);
}
.top {
background-color: rgba(255, 0, 255, 0.5); /* Magenta */
transform: rotateX(90deg) translateZ(100px);
}
.bottom {
background-color: rgba(0, 255, 255, 0.5); /* Cyan */
transform: rotateX(-90deg) translateZ(100px);
}
@keyframes rotate {
from {
transform: rotateX(0deg) rotateY(0deg);
}
to {
transform: rotateX(360deg) rotateY(360deg);
}
}
</style>
</head>
<body>
<div class="cube-container">
<div class="cube-face front"></div>
<div class="cube-face back"></div>
<div class="cube-face right"></div>
<div class="cube-face left"></div>
<div class="cube-face top"></div>
<div class="cube-face bottom"></div>
</div>
</body>
</html>
Key improvements and explanations:
perspective
on thebody
: This creates the 3D scene and allows us to see the cube in perspective. It's crucial for the 3D effect.transform-style: preserve-3d;
on the container: This is essential. It tells the browser to render the child elements in 3D space, allowing for proper rotations and translations.translateZ()
for each face: This positions each face along the z-axis, creating the cube shape. Half the width (or height) is used for thetranslateZ
value (100px in this case since the cube is 200px).rotateX
,rotateY
,rotateZ
for rotations: Used to rotate the faces into their correct positions.rgba()
for background colors: Allows for semi-transparent faces, making the rotations more visually appealing.border
for visual separation: Adds white borders to help distinguish the faces.- Clean and organized CSS: Improved readability and maintainability.
- Comments explaining the code: Makes the code easier to understand.
This improved code creates a visually appealing rotating cube with proper 3D perspective and clearly defined faces. You can adjust the colors, size, and animation speed to customize the cube to your liking.
标签:css3,cube,translateZ,100px,transform,background,立方体,画个,255 From: https://www.cnblogs.com/ai888/p/18593015