Position a 3D Cube Face with CSS Transforms
Learn how to position faces of a CSS 3D cube using rotateX, rotateY, and translateZ. Understand preserve-3d and face positioning.
Detailed Explanation
Building 3D Cube Faces
A CSS 3D cube is built by positioning six faces in 3D space using combinations of rotateX, rotateY, and translateZ. Each face is rotated to its correct orientation and then pushed outward.
Face Positioning
.cube {
transform-style: preserve-3d;
width: 200px;
height: 200px;
position: relative;
}
.face {
position: absolute;
width: 200px;
height: 200px;
}
.front { transform: translateZ(100px); }
.back { transform: rotateY(180deg) translateZ(100px); }
.left { transform: rotateY(-90deg) translateZ(100px); }
.right { transform: rotateY(90deg) translateZ(100px); }
.top { transform: rotateX(90deg) translateZ(100px); }
.bottom { transform: rotateX(-90deg) translateZ(100px); }
Why translateZ Comes After Rotate
Transform order matters. Each face is first rotated to face the correct direction, then pushed outward by half the cube's size with translateZ. If you reverse the order, the face moves in the wrong direction before rotating.
The Container
The parent element needs perspective for the 3D effect to be visible:
.scene {
perspective: 600px;
perspective-origin: center center;
}
Interactive Cube
You can rotate the entire cube to show different faces:
.cube.show-right {
transform: rotateY(-90deg);
}
Use Case
Used for 3D image carousels, interactive product showcases, dice animations in web-based games, and creative navigation menus where each face represents a different section.