两行css代码实现瀑布流

瀑布流的布局有好多种实现的方式,随着浏览器对css3的属性的支持,发现通过CSS3的多列(Multi-column)属性,可以简单的实现类似效果。

具体步骤:

1.设置外部容器多列列数(column-count)和列间距(column-gap)

2.设置内容条目的break-inside属性为avoid,使条目总体不被打断。

html结构

<div class="container"> //最外层容器
    <div class="item">//条目
         <div class="item__content">//条目内容
            <img src=''>
         </div>
     </div>
     <div class="item">
         <div class="item__content">
              <img src=''>
         </div> 
     </div>
     <!-- more items --> 
        .........
</div>

css代码

.container {
    column-count: 2; //多列的列数
    column-gap: 0;//列间距
 }

.item{
    break-inside: avoid;//避免在主体框中插入任何中断(页面,列或区域)。
}

说明:不存在一边列表过长问题,很均匀,但是存在一点问题

这个列表显示顺序是 左边 123右边456,不符合正常展示逻辑;

所以需要用js对数据进行一下预处理

const oldList = [1, 2, 3, 4, 5, 6, 7]

// 使用reduce函数接受一个初始值{ 0: [], 1: [], length: 2 },
// 初始值包含两个空数组,和一个数组长度(Array.from方法要求将对象转数组时对象内要有这个属性) 
// 在reduce函数内根据索引做余2判断,因为分两列,余0的加入第一个数组,余1的加入第二个数组 
// 最后reduce返回遍历完的对象 {0:[1,3,5,7],1:[2,4,6],length:2}
// 使用Array.from({0:[1,3,5,7],1:[2,4,6],length:2}) 得到 数组 [[1,3,5,7],[2,4,6]]
// 解构数组 使用concat合并,完事
const newList = [].concat(...(Array.from(oldList.reduce((total, cur, index) => {
  total[index % 2].push(cur)
  return total
}, { 0: [], 1: [], length: 2 }))))

console.log(newList)

输出

[1, 3, 5, 7, 2, 4, 6]

这样处理一下就可以 让列表展示顺序变为 左边 1, 3, 5, 7 右边 2, 4, 6

如果你用的老版浏览器可能存在兼容问题,就再多加几个重复的兼容浏览器的属性就行了,如下:

-moz-column-count:2; /* Firefox */
-webkit-column-count:2; /* Safari 和 Chrome */
column-count:2;

-moz-column-gap:0; /* Firefox */
-webkit-column-gap:0; /* Safari 和 Chrome */
column-gap:0;

write by :tuantuan

原文地址:https://www.cnblogs.com/widgetbox/p/13212378.html