In this post I will try to show you how create 3D Rubkik's Cube using only CSS3 and HTML. On the picture below you can see effect of my work.
Screenshot of code result. |
Theory
Time for practice.
.cube div:nth-child(1){ /*front*/ transform: translateZ(50px); background-color : #fff; } .cube div:nth-child(2){ /*top*/ transform: rotateX(90deg) translateZ(50px); background-color : yellow; } .cube div:nth-child(3){/*bottom*/ transform: rotateX(-90deg) translateZ(50px); background-color : orange; } .cube div:nth-child(4){ /*left*/ transform: rotateY(-90deg) translateZ(50px); background-color : red; } .cube div:nth-child(5){ /*right*/ transform: rotateY(90deg) translateZ(50px); background-color : green; } .cube div:nth-child(6){ /*back*/ transform: translateZ(-50px); background-color : blue; }
To see cube in 3D we need add preserve-3d as a parameter of transform-style property. To do this I add div with id main and set these style for this div. Then I put our .cube div inside it #main. Our html should look like this:
<div id="main"> <div class="cube"> <div></div><div></div><div></div><div></div><div></div><div></div> </div> </div>
To see effect I also rotate our cube: transform: rotateX(335deg) rotateY(335deg) rotateZ(0deg); and add some css rules for better view of result:
body { background: #333; } #main{ width: 300px; height: 300px; margin: 0 auto; margin-top: 150px; transform: rotateX(335deg) rotateY(335deg) rotateZ(0deg); transform-style: preserve-3d; transform-origin: 50% 50%; } .cube{ opacity: 1; position: absolute; height: 100px; width: 100px; } .cube div{ position: absolute; height: 60px; width: 60px; padding: 18px; border: 3px solid #000; border-radius: 5px; }
Now just 26 cubes more to finish...
Not exactly. It will be easy if we group our cubes into groups.
Columns
I start by adding 2 more cubes and also adding to each class col as a column and to each individually classes col1, col2 and col3. Now time to set each of this item (col1 in default is set in start position):div.col2{ transform: translateX(100px); } div.col3{ transform: translateX(200px); }
div.col{ transform-style: preserve-3d; }
Rows
div.row1{ transform: translateZ(-150px); } div.row2{ transform: translateZ(-50px); } div.row3{ transform: translateZ(50px); }
div.col, div.row{ transform-style: preserve-3d; }
Levels
div.lvl2{ transform: translateY(100px); } div.lvl3{ transform: translateY(200px); }
No comments :
Post a Comment