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 脚本实现,列如:MasonryIsotopeJustified-GalleryPackerybricks.jsflexImagesjQuery-flexImageswaterfall

相关推荐
EndingCoder14 分钟前
类的继承和多态
linux·运维·前端·javascript·ubuntu·typescript
用户479492835691516 分钟前
React 终于出手了:彻底终结 useEffect 的"闭包陷阱"
前端·javascript·react.js
程序员猫哥22 分钟前
前端开发,一句话生成网站
前端
Younglina43 分钟前
一个纯前端的网站集合管理工具
前端·vue.js·chrome
木头程序员44 分钟前
前端(包含HTML/JavaScript/DOM/BOM/jQuery)基础-暴力复习篇
开发语言·前端·javascript·ecmascript·es6·jquery·html5
卖火箭的小男孩1 小时前
# Flutter Provider 状态管理完全指南
前端
小雨青年1 小时前
鸿蒙 HarmonyOS 6|ArkUI(01):从框架认知到项目骨架
前端
Null1551 小时前
浏览器唤起本地桌面应用(基础版)
前端·浏览器
pas1361 小时前
31-mini-vue 更新element的children
前端·javascript·vue.js
wordbaby1 小时前
TanStack Router 实战:如何构建经典的“左侧菜单 + 右侧内容”后台布局
前端·react.js