1. 程式人生 > 實用技巧 >CSS3中的3D效果

CSS3中的3D效果

相對於2D多了一個Z軸,垂直於螢幕

transform屬性

transform:向元素應用2D或者3D轉換,在3D效果下可結合translate平移,rotate()旋轉,skew()扭曲,scale()縮放

transform-origin:被轉換元素的中心位置,預設在中心

transform-style:開啟3D模式的屬性

  flat:子元素不保留3D位置

  preserve-3d:子元素保留3D位置,開啟3D模式

perspective:視點

  none:沒有3D空間

  取值越小,3D效果越明顯,0或者無窮大等價於none

perspective-origin:視點的位置

backface-visibility:設定當前元素不面向螢幕是否可見

  visible:預設值,可見

  hidden:不可見

總的來說3D效果實現紙面上看起來很簡單,但需要自己去體會,以下是旋轉立方體程式碼,可以自己嘗試寫一寫,感受一下各個屬性:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CSS3實現旋轉立方體</title>
        <style type="text/css">
            *{
        margin: 0;
        padding: 0;
       } ul li{
        list
-style: none;
       } .box{ width: 400px; height: 400px; border: 2px #FF0000 solid; margin: 100px auto; perspective: 1200px;/*視點遠近*/ } .box ul{ width: 300px; height: 300px; border: 1px #00f solid; margin: 50px auto; position: relative; transform
-style: preserve-3d; /*開啟3D模式*/ animation: move 2.5s infinite linear; /*animation動畫*/
/*旋轉的焦點位置,整個正方體圍繞哪個焦點旋轉,現在是圍繞正方體內部中心點*/ transform
-origin: center center 150px; } .box ul li{ width: 300px; height: 300px; font-size: 30px; color: aliceblue; text-align: center; line-height: 300px; position: absolute; }
       /*調整元素的位置,拼成正方體*/ .box ul li:nth
-of-type(1){
          background-color: red;opacity:0.4;
        } .box ul li:nth
-of-type(2){
          background-color: blue;opacity:0.4;
          transform: translateX(300px)rotateY(-90deg);
          transform-origin: left ;
       } .box ul li:nth
-of-type(3){
          background-color: yellow;
          opacity:0.4;
          transform: translateX(-300px)rotateY(90deg);
          transform-origin: right;
        } .box ul li:nth
-of-type(4){
          background-color: green;
          opacity:0.4;
          transform: translateY(-300px)rotateX(-90deg);
          transform-origin: bottom;
        } .box ul li:nth
-of-type(5){
          background-color: yellowgreen;  
          opacity:0.4;
          transform: translateY(300px)rotateX(90deg);
          transform-origin: top;} .box ul li:nth-of-type(6){
          background-color: purple;
          opacity:0.4;
          transform: translateZ(300px);
        }
       /*旋轉動畫*/ @keyframes move{ from{transform: rotateY(0deg);} to{transform: rotateY(360deg);} }
</style> </head> <body> <div class="box"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> </ul> </div> </body> </html>