flex实现瀑布流布局并实现从左到右排序(order)flex结合order实现从左到右的瀑布流
这种⽅式可以做到先从左到右,再从上到下显⽰
缺点:需要预先设定flex容器的⾼度,且调整页⾯⼤⼩时会出现⼀些间距过⼤的问题
应对:列表改变时,动态计算flex所需⾼度
缺陷:整体上的每列数量还是按列平均分布的,并未进⾏填充。
关键代码
vue
html的flex布局//vue代码
watch: {
itemList(newVal) {
// 为瀑布流重新计算布局
this.$nextTick(() => {
const items = ElementsByClassName('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;
}
}
效果
参考

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。