1. 程式人生 > >【CSS】純css實現立體擺放圖片效果

【CSS】純css實現立體擺放圖片效果

1.  元素的 width/height/padding/margin 的百分比基準

設定 一個元素 width/height/padding/margin 的百分比的時候,大家可知道基準是什麼?

舉個栗子:

.parent {
  width: 200px;
  height: 100px;
}
.child {
  width: 80%;
  height: 80%;
}
.childchild {
  width: 50%;
  height: 50%; padding: 2%;  margin: 5%;
} 
    <div class="parent">
        <div class="child">
            <div class="childchild"></div>
        </div>
    </div>

  上段程式碼中,childchild 元素的 width 是多少? height 是多少?padding 是多少? margin是多少?

元素的 height 百分比基準是父級元素的 height, 元素的 width, padding, margin 百分比基準是父級元素的 width。

由此,相信大家都已經有數了,大家可以試一下呢~~

面試經常會遇到一個簡單的css樣式問題 , 實現一個自適應的正方形,原理就是基於上面的那些知識了。只需要

#box {
            width: 50%;
            padding-top: 50%;
            background: #000;
        }

  因為元素的 width 和 padding 的基準值都是父級元素的 width, 而 body 的 width 就是瀏覽器視窗啦~~,so 這樣設定就可以隨著瀏覽器視窗大小變化,正方形自適應了呢~~

2. 純css實現立體擺放圖片效果

言歸正傳,想要實現如下圖中圖片的立體擺放效果,就需要應用一下 padding ,width, height 的知識了。

有點眼熟,是不是跟小說軟體裡推薦圖書的樣式有些相似呢?

這裡,首先我們看下其位置擺放,一張圖片水平居中並且靠前,其他兩邊圖片分別左右對齊,並且靠後一些,呈現一種立體擺放的樣子。這裡我學到了一種完全依賴css,簡單的寫法即可實現這種立體的效果。

 · 不同的高度是 padding-top 有大有小撐起來的。

 · 前後效果是 z-index 摺疊順序控制的。

 · 排列上使用了 nth-of-type 偽元素控制 + positon 定位結合。

是不是有點思路了呢?不繞彎子了,直接上程式碼

<html>
    <head>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            .box {
                width: 300px;
                height: 200px;
                position: relative;
            }
            .img {
                width: auto;
                height: 0;
            }
            .box img {
                width: 100%;
                display: inline-block;
            }
            .box .img:nth-of-type(1) {
                display: inline-block;
                position: absolute;
                left: 50%;
                top: 50%;
                padding-bottom: 50%;
                transform: translate(-50%, -50%);
                z-index:  6;
            }
            .box .img:nth-of-type(2), .box .img:nth-of-type(3) {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                padding-bottom: 63%;
                z-index: 3;
            }
            .box .img:nth-of-type(2) {
                right: 0;
            }
            .box .img:nth-of-type(3) {
                left: 0;
            }
        </style>
    </head>
    <body>
        <div class="box">
            <div class="img">
                <img src="https://febaidu.com/list/img/3ns.png" />
            </div>
            <div class="img">
                <img src="https://febaidu.com/list/img/3ns.png" />
            </div>
            <div class="img">
                <img src="https://febaidu.com/list/img/3ns.png" />
            </div>
        </div>
    </body>
</html>

  快去試試吧 ~