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;
  }
}

效果

posted @   朝日asahi  阅读(3312)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示