瀑布流布局,在各大电商网站中都可以看到。以前想要实现瀑布流布局,都是使用JavaScript或jQuery来实现,代码比较复杂。现在有了CSS3,我们只需要几行代码就可以轻松做到了。

实现代码如下:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .container { column-width: 160px; column-gap: 5px; } .container div { width: 160px; margin: 4px 0; } </style> </head> <body> <div class="container"> <div><img src="img/column/pic1.jpg" /></div> <div><img src="img/column/pic2.jpg" /></div> <div><img src="img/column/pic3.jpg" /></div> <div><img src="img/column/pic4.jpg" /></div> <div><img src="img/column/pic5.jpg" /></div> <div><img src="img/column/pic6.jpg" /></div> <div><img src="img/column/pic7.jpg" /></div> <div><img src="img/column/pic8.jpg" /></div> <div><img src="img/column/pic9.jpg" /></div> <div><img src="img/column/pic10.jpg" /></div> <div><img src="img/column/pic11.jpg" /></div> <div><img src="img/column/pic12.jpg" /></div> <div><img src="img/column/pic13.jpg" /></div> <div><img src="img/column/pic14.jpg" /></div> <div><img src="img/column/pic15.jpg" /></div> <div><img src="img/column/pic16.jpg" /></div> <div><img src="img/column/pic17.jpg" /></div> <div><img src="img/column/pic18.jpg" /></div> <div><img src="img/column/pic19.jpg" /></div> <div><img src="img/column/pic20.jpg" /></div> <div><img src="img/column/pic1.jpg" /></div> <div><img src="img/column/pic2.jpg" /></div> <div><img src="img/column/pic3.jpg" /></div> <div><img src="img/column/pic4.jpg" /></div> <div><img src="img/column/pic5.jpg" /></div> <div><img src="img/column/pic6.jpg" /></div> <div><img src="img/column/pic7.jpg" /></div> <div><img src="img/column/pic8.jpg" /></div> <div><img src="img/column/pic9.jpg" /></div> <div><img src="img/column/pic10.jpg" /></div> <div><img src="img/column/pic11.jpg" /></div> <div><img src="img/column/pic12.jpg" /></div> <div><img src="img/column/pic13.jpg" /></div> <div><img src="img/column/pic14.jpg" /></div> <div><img src="img/column/pic15.jpg" /></div> <div><img src="img/column/pic16.jpg" /></div> <div><img src="img/column/pic17.jpg" /></div> <div><img src="img/column/pic18.jpg" /></div> <div><img src="img/column/pic19.jpg" /></div> <div><img src="img/column/pic20.jpg" /></div> </div> </body> </html>

浏览器预览效果如下图所示。

分析:

瀑布流布局的特点是每列的宽度是相同的,但是高度是随机的。然后我们只需要定义column-width跟每列的width相等。两行代码就可以实现这么棒的效果,CSS3是不是非常神奇呢?