CSS CSS Transitions and Transforms Adding 3D Effects with CSS Build a Rotating 3D Cube

jaspergradussen
jaspergradussen
5,876 Points

Handy way to make a 3d cube!

Code used:

.front { transform: translateZ(110px); }

.back { transform: rotateY(270deg) translateZ(110px); }

.right { transform: rotateY(90deg) translateZ(110px); }

.left { transform: rotateY(180deg) translateZ(110px); }

  1. First I visualise how much I want to rotate each face/side of the cube. So say the back-side. Well the back-side is actually the left-side since it rotates -270 degrees (so 0.75turn counter-clock-wise). (but for the sake of consistency with the rest of the code, I keep the naming the name with the index.html).
  2. Apparently the order in which the transform is applied matters!!! So. When a rotate around any axis is applied, then the axis of translateX,Y,Z is also rotated. So when you preview transform:rotateY(270deg); You see the rotation is applied (0.75turns clock-wise). And then you simply have to bring forward (relative to center). That is because the Z-axis (the front&back one, also rotated!). See the pattern in the code? I simply cover all angles > by 0/360deg (front), 90 , 180, 270deg, and then because the axis is also rotated, just bring it forward from that rotation. That makes it very intuitive for me.

For clarification: This is the first time I am doing this, but I have found it to work just fine! If any of you know why I made this is less efficient then the code that Guil wrote, please let me know.

I tested my findings on a 6 sided object. Same rules. 360(deg)/6 (sides) = 60deg. And then bring the face forward on the (rotated) Z-axis. The distance from the center is not the 110px anymore (like in the example), but with some math you can figure that one out. Or keep the relative distance from the center and cut in the width of the sides (otherwise the objects get bigger... up to you!) Good luck everyone!!!