1. 程式人生 > >CSS3 之 立方體

CSS3 之 立方體

 利用CSS3屬性在頁面中寫出立體的3d盒子

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    /* 
      如果有多個元素都有3d效果,那麼只需要給最外成的祖先元素新增perspective即可
    
     */
    /*清除需要的樣式*/
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
    }
    /*給body新增3D效果,並加上視距*/
    body {
      transform-style: preserve-3d;
      perspective: 500px;

    }
    /* 給盒子新增視距*/
    .box {
      position: relative;
      width: 200px;
      height: 200px;
      margin: 100px auto;
      transform-style: preserve-3d;
      transition: all 5s;
      transform: rotateY(0deg) rotateX(0deg);    }
    /*body:hover的過渡效果*/
    body:hover .box {
      transform: rotateY(360deg) rotateX(360deg);
    }
    /*接下來就是角度還有距離的偏移以及偏轉*/
    .item {
      position: absolute;
      top: 0;
      left: 0;
      width: 200px;
      height: 200px;
      text-align: center;
      line-height: 200px;
      color: #fff;
      font-size: 72px;
      background: rgba(0, 0, 0, .6);
      box-sizing: border-box;
      border: 2px solid #eee;
      transition: all 5s;
    }

    .item:nth-child(1) {
      transform: rotateX(90deg) translateZ(100px);
    }

    .item:nth-child(2) {
      transform: rotateX(-90deg) translateZ(100px);
    }

    .item:nth-child(3) {
      transform: rotateY(-90deg) translateZ(100px);
    }

    .item:nth-child(4) {
      transform: rotateY(90deg) translateZ(100px);
    }

    .item:nth-child(5) {
      transform: translateZ(100px);
    }

    .item:nth-child(6) {
      transform: rotateY(180deg) translateZ(100px);
    }

    .box:hover .item:nth-child(1) {
      transform: rotateX(90deg) translateZ(150px);
    }

    .box:hover .item:nth-child(2) {
      transform: rotateX(-90deg) translateZ(150px);
    }

    .box:hover .item:nth-child(3) {
      transform: rotateY(-90deg) translateZ(150px);
    }

    .box:hover .item:nth-child(4) {
      transform: rotateY(90deg) translateZ(150px);
    }

    .box:hover .item:nth-child(5) {
      transform: translateZ(150px);
    }

    .box:hover .item:nth-child(6) {
      transform: rotateY(180deg) translateZ(150px);
    }
  </style>
</head>

<body>
  <ul class="box">
    <li class="item">上</li>
    <li class="item">下</li>
    <li class="item">左</li>
    <li class="item">右</li>
    <li class="item">前</li>
    <li class="item">後</li>
  </ul>

</body>

</html>