How to create cube with only HTML and CSS?

前端 未结 9 2079
星月不相逢
星月不相逢 2021-01-30 17:03

I have this and I want to make a cube with HTML & CSS only like in the above image. My best try:

9条回答
  •  灰色年华
    2021-01-30 17:39

          y         
          |          
          |____ x 
         ╱        
        z 
    

    Imagine a cube from the front side. What you can see? A square that comes out over the screen. So, for the front side, we have:

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

    for the right side, we have a square that is rotated 90 degrees on Y-Axis and moved on own new Z-Axis:

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

    for the left side, we have a square that is rotated -90 degrees on Y-Axis and moved on own new Z-Axis:

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

    for the top side, we have a square that is rotated 90 degrees on X-Axis and moved on own new Z-Axis:

    .right {
      transform : rotateX(90deg) translateZ(50px);
    }
    

    for the back side, we have a square that is rotated -180 degrees on Y-Axis and moved on own new Z-Axis:

    .right {
      transform : rotateY(-180deg) translateZ(50px);
    }
    

    Then, Just package them in a shape container class with transform-style: preserve-3d property:

    .cube {
      transform-style: preserve-3d;
    }
    

    finally, you can rotate your cube and see the CSS-3D magic.

    .cube {
      transform-style: preserve-3d;
      transform: rotateX(-40deg) rotateY(45deg);
    }
    

    .cube {
      transform-style: preserve-3d;
      transform: rotateX(-40deg) rotateY(45deg);
    }
    
    .side {
      position: absolute;
      width: 100px;
      height: 100px;
      background: #c52329;
      border: solid 3px white;
    }
    
    .front {
      transform: translateZ(53px);
    }
    
    .top {
      transform: rotateX(90deg) translateZ(53px);
    }
    
    .right {
      transform: rotateY(90deg) translateZ(53px);
    }
    
    .left {
      transform: rotateY(-90deg) translateZ(53px);
    }
    
    .bottom {
      transform: rotateX(-90deg) translateZ(53px);
    }
    
    .back {
      transform: rotateY(-180deg) translateZ(53px);
    }
    It is a full cube. For your approach, you can ignore the back, right, and bottom sides.

    Thanks to css-tricks.com

提交回复
热议问题