作者:MudOnTire
轉發鏈接:https://segmentfault.com/a/1190000023103516
前言
瀑布流提供了一種錯落有致的美觀布局,被各種注重交互品味的素材網站(如:花瓣、unsplash)廣泛應用。社區也提供了不少瀑布流布局的工具,如:masonry 、colcade 等。常規的實現瀑布流的做法是用 JS 動態的計算“磚塊”的尺寸和位置,計算量大、性能差。今天給大家介紹一種使用純 css 實現瀑布流的方法,簡潔優雅。主要使用到了 CSS 中的多列屬性 columns。
在使用一個比較陌生的 CSS 屬性之前,習慣性的了解一下它的兼容性,去 caniuse.com 瞅一眼:

看著兼容性還不錯,那就放心的用吧。
html
先構造頁面結構:
<div class="masonry">
<div class="item">
<img src="http://source.unsplash.com/random/400x600" />
<h2>Title Goes Here</h2>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quis quod et
deleniti nobis quasi ad, adipisci perferendis totam, ducimus incidunt
dolore aut, quae quaerat architecto quisquam repudiandae amet nostrum
quidem?
</p>
</div>
...more...
</div>
在 div.masonry 容器中可以塞進任意多的 “磚塊” div.item,“磚塊” 中的圖片可以從 unsplash 中隨機獲取,且可以制定圖片的尺寸。
CSS
容器:
.masonry {
width: 1440px; // 默認寬度
margin: 20px auto; // 劇中
columns: 4; // 默認列數
column-gap: 30px; // 列間距
}
磚塊:
.item {
width: 100%;
break-inside: avoid;
margin-bottom: 30px;
}
.item img {
width: 100%;
}
.item h2 {
padding: 8px 0;
}
.item P {
color: #555;
}
上面的樣式其他都挺好理解,唯獨 break-inside 這個屬性比較陌生。讓我們看一下去掉 break-inside 之后會有什么問題吧:

可以看到有兩個“磚塊”的文字跑到上面和圖片分開了。所以當設置了 break-inside: avoid 之后可以避免“磚塊”內部的內容被斷開。
不同屏幕尺寸適配
以上樣式默認適配 PC,在其他尺寸設備上需要重新設置列數、列間距等樣式,可以通過 media query 進行適配,比如:
ipad pro:
@media screen and (min-width: 1024px) and (max-width: 1439.98px) {
.masonry {
width: 96vw;
columns: 3;
column-gap: 20px;
}
}
ipad:
@media screen and (min-width: 768px) and (max-width: 1023.98px) {
.masonry {
width: 96vw;
columns: 2;
column-gap: 20px;
}
}
mobile:
@media screen and (max-width: 767.98px) {
.masonry {
width: 96vw;
columns: 1;
}
}
注意:屏幕尺寸區間不要有交集,也不要有缺口!
好了,大功告成,來張全家福!

作者:MudOnTire
轉發鏈接:https://segmentfault.com/a/1190000023103516