CSS實現相簿橫向完美排布方法

來源:互聯網
上載者:User

最近要做一個相簿頁面,碰到的第一個問題就是如何排布。本文我們將帶大家來看一個關於CSS解決相簿橫向完美排布例子的,希望這個例子能夠為各位同學帶來協助了,有興趣的一起來看看吧。

分析一下,有一個容器,容器有padding,每一行的每一個item之間又有margin,首先想到的是這樣

<pre class="brush:css;toolbar:false">.container {        padding: 10px;    }            .container .item      {        float: left;        width: 24%;        margin-left: 1%;        border: 1px solid #CCC;         }       </pre>

然而,這種情況會造成兩個問題,首先第一個是第一個item自身的margin-left加上.container的padding會造成左邊空白比上下左右都要大,還會造成item與item之間的垂直間距與水平間距不能控制到一樣的大小。
於是考慮到使用calc屬性

<pre class="brush:css;toolbar:false">.container {        padding: 5px;    }         .container .item    {        width: 25%;        position: relative;        float: left;    }            /* 這個圖片僅僅是為了擷取寬高,實際是看不見的 */    .container .item >         img {        opacity: 0;        width: 100%;       }                      /* 這個才是每一個item裡容器    .container .item .body                {        border: 1px solid #CCC;        width: calc(100% - 10px);                        height: calc(100% - 10px);                              margin: auto;                                    left: 0;                                         top: 0;                                              bottom: 0;                                                    right: 0;                                                      }                                                    </pre>

以上代碼如果要是用sass來實現的話,更容易了,這種實現方法相當於實際上每一個item佔用的大小就是25%,只是裡面的body都上下左右都有5px的邊距。item與item之間的邊距實際上就是每一個item的右間距加上右邊item的左邊距,每一個item的下邊距加上它下方item的上邊距。

這種實現方法有幾個好處:


1、上下左右都是一樣的邊距
2、純樣式
3、圖片比例不會被破壞

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.