1. 程式人生 > >CSS 詳細深入理解3D轉換模組

CSS 詳細深入理解3D轉換模組

什麼是2D和3D

2D就是一個平面, 只有寬度和高度, 沒有厚度 3D就是一個立體, 有寬度和高度, 還有厚度 預設情況下所有的元素都是呈2D展現的

 

如何讓某個元素呈3D展現

和透視一樣, 想看到某個元素的3d效果, 只需要給他的父元素新增一個transform-style屬性, 然後設定為preserve-3d即可

 

2D效果:

 

 

3D效果:

 

對比很明顯,3D顯示能展現出子元素穿插父元素,而2D顯示,把元素都侷限在了一個平面上,所以,3D模組讓元素有了一個“厚度”屬性,而2D模組僅僅只有長度和寬度屬性,這就是他們兩者的區別。

3D模組寫法:

.father{
            width: 200px;
            height: 200px;
            background-color: red;
            border: 1px solid #000;
            margin: 100px auto;
            perspective: 500px;
            /*
          想看到某個元素的3d效果, 只需要給他的父元素新增一個transform-style屬性,
            然後設定為preserve-3d即可
            */
            transform-style: preserve-3d;
            transform: rotateY(0deg);
        }

注意是父元素!!!

在平時的應用中,3D模組常常用於做正方體或者長方體,要實現這個,他就要它transform中的translate屬性聯合使用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>108-3D轉換模組-正方體終極</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        ul{
            width: 200px;
            height: 200px;
            border: 1px solid #000;
            box-sizing: border-box;
            margin: 100px auto;
            position: relative;
            transform: rotateY(0deg) rotateX(0deg);
            transform-style: preserve-3d;
        }
        ul li{
            list-style: none;
            width: 200px;
            height: 200px;
            font-size: 60px;
            text-align: center;
            line-height: 200px;
            position: absolute;
            left: 0;
            top: 0;
        }
        ul li:nth-child(1){
            background-color: red;
            transform: rotateX(90deg) translateZ(100px);
        }
        ul li:nth-child(2){
            background-color: green;
            transform: rotateX(180deg) translateZ(100px);
        }
        ul li:nth-child(3){
            background-color: blue;
            transform: rotateX(270deg) translateZ(100px);
        }
        ul li:nth-child(4){
            background-color: yellow;
            transform: rotateX(360deg) translateZ(100px);
        }
        ul li:nth-child(5){
            background-color: purple;
            transform: translateX(-100px) rotateY(90deg);
        }
        ul li:nth-child(6){
            background-color: pink;
            transform: translateX(100px) rotateY(90deg);
        }

    </style>
</head>
<body>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>
</body>
</html>

這裡面需要注意的是,在元素髮生旋轉之後,它的座標軸也會隨之旋轉,自己要模擬一下。