How to create cube with only HTML and CSS?

前端 未结 9 1977
星月不相逢
星月不相逢 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 18:00

    You can also achieve a cube with 3d transforms. This will give your cube a more realistic perspective. As if the cube was a real 3d shape like this:

    In the following I used one div with 2 pseudo elements :

    body {
      perspective: 900px;
      padding-bottom:50%;
    }
    div {
      position: relative;
      width: 20%;
      padding-bottom: 20%;
      margin: 0 auto;
      transform-style: preserve-3d;
      background: #C52329;
      transform: rotateX(60deg) rotatez(45deg);
    }
    div:before, div:after {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      transform-origin: -2% -2%;
      background: inherit;
    }
    div:before {
      top: 104%; left: 0;
      transform: rotateX(-90deg);
    }
    div:after {
      top: 0; left: 104%;
      transform: rotateY(90deg);
    }

    CSS 3d cube with 6 faces:

    This technique allows you to make a "real cube" with 6 faces:

    body{
      perspective-origin:50% -100%;
      perspective: 900px;
      overflow:hidden;
    }
    h1{position:absolute;font-family:sans-serif;}
    .cube {
      position:relative;
      padding-bottom:20%;
      transform-style: preserve-3d;
      transform-origin: 50% 100%;
      transform:rotateY(45deg) rotateX(0);
      transition:transform 3s;
    }
    .cubeFace {
      position: absolute;
      left:40%;top:0;
      width: 20%;height:100%;
      margin: 0 auto;
      transform-style: inherit;
      background: #C52329;
      box-shadow:inset 0 0 0 5px #fff; 
      transform-origin:50% 50%;
      transform: rotateX(90deg);
      backface-visibility:hidden;
    }
    .face2{
      transform-origin:50% 50%;
      transform: rotatez(90deg) translateX(100%) rotateY(90deg);
    }
    .cubeFace:before, .cubeFace:after {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      transform-origin:0 0;
      background: inherit;
      box-shadow:inherit;
      backface-visibility:inherit;
    }
    .cubeFace:before {
      top: 100%; left: 0;
      transform: rotateX(-90deg);
    }
    .cubeFace:after {
      top: 0; left: 100%;
      transform: rotateY(90deg);
    }
    
    body:hover .cube{
      transform:rotateY(405deg) rotateX(360deg);
    }

    Hover me:

    Note that I didn't add the vendor prefixes in the examples. For more info about browser support and what vendor prefixes are needed according to your target audience, see canIuse for 3d transforms.

提交回复
热议问题