在项目开发中,为实现瀑布流效果而引入JS库很麻烦,并且性能较低,相比之下纯CSS写法有多方面优势。
首先Chrome Canary新特性 grid-template-rows: masonry配合display:grid和grid-template-columns可以实现
<style>
.container{
display: grid;
grid-template-columns: repeat(2, 1fr); //2代表2列,1fr为100%剩余空间
grid-gap: 10px; //列间间隔
grid-template-rows:masonry; //新特性,砖石结构
}
.container > .item{
display:block;
width:100%;
}
</style>
但使用这个属性不现实,因为你的客户可能会把你撕了,等几年再说吧。
还有一种纯CSS方式,使用flex实现,但这种效果不佳,需要固定容器高度,不容易控制列数如下
<style>
.container{
display: flex;
height: 500px;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
}
.container > .item{
display:block;
width:45%;
height:auto;
}
</style>
那么目前效果比较好的方式如下:
<style>
.container{
column-count: 2;
column-gap: 10px;
}
.container > .item{
width: 100%;
break-inside: avoid; //重要属性,防止容器内部元素被分开放于两列
-webkit-column-break-inside: avoid;
margin-bottom: 10px; //容器内部元素垂直方向的间距
}
</style>