纯CSS写瀑布流,简单的完美实践

在项目开发中,为实现瀑布流效果而引入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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值