CSS 瀑布流图片简易实现

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
	  .waterfall {
	    column-count: 3;
	    column-gap: 10px;
	  }
	  .waterfall-item {
	    break-inside: avoid;
	    margin-bottom: 10px;
	    display: block;
	  }
	  .waterfall-item img {
	    width: 100%;
	    height: auto;
	    display: block;
	  }
	</style>
  </head>
  <body>
    <div class="waterfall">
      <div class="waterfall-item">
        <img src="img1.jpg" alt="" />
      </div>
      <div class="waterfall-item">
        <img src="img2.jpg" alt="" />
      </div>
      <div class="waterfall-item">
        <img src="img3.jpg" alt="" />
      </div>
    </div>
  </body>
</html>

使用 float: left(float常规浮动,高度固定、不铺满)

html 复制代码
<style>
  .waterfall {
    display: block;
    margin-right: -10px;
    margin-bottom: -10px;
  }

  .waterfall-item {
    float: left;
    height: 300px;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .waterfall-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

使用 flex-wrap: wrap(flex常规浮动,高度固定)

html 复制代码
<style>
  .waterfall {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .waterfall-item {
    flex: 1;
    height: 300px;
    min-width: 200px;
    max-width: 500px;
  }

  .waterfall-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

使用 column-count (列数固定,宽高自适应)

html 复制代码
<style>
  .waterfall {
    column-count: 3;
    column-gap: 10px;
  }
  .waterfall-item {
    break-inside: avoid;
    margin-bottom: 10px;
    display: block;
  }
  .waterfall-item img {
    width: 100%;
    height: auto;
    display: block;
  }
</style>

使用 Grid + grid-auto-flow: dense(列数变化,宽高自适应,每个item宽高相等)

html 复制代码
<style>
  .waterfall {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    grid-auto-rows: 200px;
    grid-gap: 10px;
    grid-auto-flow: dense;
  }

  .waterfall-item {
    grid-row: span 1;
    overflow: hidden;
    border-radius: 8px;
  }

  .waterfall-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

想要高可控效果可借助 javascrpit 脚本实现,列如:Masonry 、Isotope、Justified-Gallery、Packery、bricks.js 、flexImages、jQuery-flexImages、waterfall

相关推荐
CoovallyAIHub43 分钟前
用 AI 做 PPT 被辞退,法院判公司赔:员工贴进对话框的数据,到底谁负责?
前端·agent
fruge1 小时前
SSH、RDP、VNC不必各开一个客户端:Next Terminal用Web入口统一管理远程资产和会话记录
运维·前端·ssh
honkun61 小时前
vue 下拉树组件 vxe-table-select 实现分页多选
前端·javascript·vue.js
用户621007587022 小时前
Web BIM 开发实践:如何将构件选择、属性查询接入业务系统?
前端
羲云2 小时前
AI 分站搭完就能发链接?上线前先过这 5 关
前端
葡萄城技术团队2 小时前
一个 F4 快捷键,为什么能决定 Web 表格是否像 Excel?
前端
王川7082 小时前
商协会后台前端的模块聚合实践
前端·后端
jerrywus2 小时前
Codex、Claude Code、DSH 怎么用手机管?我试了试 Agents Anywhere
前端·claude·deepseek
twj_5022 小时前
农业商业计划书PPT制作完全指南
前端