flex实现瀑布流布局并实现从左到右排序(order)
flex结合order实现从左到右的瀑布流
这种方式可以做到先从左到右,再从上到下显示
缺点:需要预先设定flex容器的高度,且调整页面大小时会出现一些间距过大的问题
应对:列表改变时,动态计算flex所需高度
缺陷:整体上的每列数量还是按列平均分布的,并未进行填充。
关键代码
- vue
//vue代码
watch: {
itemList(newVal) {
// 为瀑布流重新计算布局
this.$nextTick(() => {
const items = document.getElementsByClassName('catalog-item')
let totalHeight = 0
// 计算每列的高度
const columnHeights = [0, 0, 0, 0]
for (let i = 0; i < items.length; i++) {
totalHeight += items[i].clientHeight
columnHeights[i % 4] += items[i].clientHeight
}
this.panelHeight = totalHeight / 4 + 100
// document.body.style.setProperty('--waterfallHeight', `${(totalHeight + maxHeight) / 4}px`)
// 设置最高列为高度
document.body.style.setProperty('--waterfallHeight', `${Math.max(...columnHeights) + 10}px`)
})
}
},
- css
.catalog-list {
display:flex;
// margin:0 auto;
flex-direction: column;
flex-wrap: wrap;
height: var(--waterfallHeight, 5000px);
}
.catalog-item {
// box-sizing: border-box;
// break-inside:avoid;
position: relative;
width: 300px;
padding: 20px;
padding-bottom: 35px;
counter-increment: item-counter;
//改变元素排序,使其成为由左至右的瀑布流
&:nth-child(4n+1){
order:0;
}
&:nth-child(4n+2){
order:1;
}
&:nth-child(4n+3){
order:2;
}
&:nth-child(4n+4){
order:3;
}
}