Course Technology Cengage Learning New Perspectives on HTML5 and CSS3, 8th Edition
Tutorial 4

3D Cube

This shows how to create a 3D cube. The six faces of the cube are placed within a container element (with the ID "cube" in this example.) The perspective of the cube is passed to the 6 faces using the transform-style: preserve-3d style. Each face is placed in position by rotating and translating it along one of 6 directions.

Click the [Front] through [Top] buttons to animate the process by which faces are added to the cube. Once all six faces are assembled, you can rotate the entire cube using the rotation sliders. Since each face exists in the same 3D space, they will rotate along with the cube. The HTML and CSS code for assembling the cube and running the rotation is shown below. Note that this example uses square faces that are 300 pixels wide and high and translated 150 pixels along the x, y, and z axes. For larger or smaller cubes, you can rescale these dimensions.

CSS Cubes

Insert Cube Face


Rotate Cube

-360deg 360deg
-360deg 360deg
-360deg 360deg

HTML

<div id="container" >
     <div id="cube" >
          <div id="front" > ... </div>
          <div id="back" > ... </div>
          <div id="bottom" > ... </div>
          <div id="left" > ... </div>
          <div id="right" > ... </div>
          <div id="top" > ... </div>
     </div>
</div>

CSS

div#container {
    perspective: 1500px;
}
div#cube {
   position: relative;
   transform-style: preserve-3d;
   transform: rotateX(-24deg) rotateY(-40deg) rotateZ(0deg);
}
div#cube div.faces {
   position: absolute; top: 0; left: 0;
}
div#front { transform: rotateY(0deg) translateZ(150px); }
div#back { transform: rotateY(180deg) translateZ(150px); }
div#bottom { transform: rotateX(-90deg) translateZ(150px); }
div#left { transform: rotateY(-90deg) translateZ(150px); }
div#right { transform: rotateY(90deg) translateZ(150px); }
div#top { transform: rotateX(90deg) translateZ(150px); }
FRONT
BACK
BOTTOM
LEFT
TOP