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

相关推荐
yinuo6 分钟前
纯CSS&JS实现:丝滑渐变过渡的动态导航栏
前端
qq. 28040339847 分钟前
vue介绍
前端·javascript·vue.js
未来之窗软件服务11 分钟前
未来之窗昭和仙君(五十五)标签票据打印模板设计器——东方仙盟筑基期
前端·打印设计器·仙盟创梦ide·东方仙盟·昭和仙君·东方仙盟架构
Mr.Jessy19 分钟前
Web APIs 学习第五天:日期对象与DOM节点
开发语言·前端·javascript·学习·html
前端大卫20 分钟前
如何统一前端项目的 Node 版本和包管理器?
前端
Hi~晴天大圣1 小时前
HTML onclick用法
前端·html
速易达网络1 小时前
HTML<output>标签
javascript·css·css3
!win !2 小时前
前端跨标签页通信方案(上)
前端·javascript
xw52 小时前
前端跨标签页通信方案(上)
前端·javascript
烛阴2 小时前
Python数据可视化:从零开始教你绘制精美雷达图
前端·python