You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建根据列表内图片数量动态调整的grid布局?

实现方案

你可以通过固定2列的grid布局配合子元素数量选择器实现需求,代码如下:

1. HTML结构示例

<!-- 列表项示例 -->
<div class="list-item">
  <p>列表项文本内容</p>
  <div class="img-grid">
    <!-- 这里放入动态生成的img标签 -->
    <img src="xxx.png" alt="示例图">
  </div>
</div>

2. CSS代码

/* 图片容器grid配置 */
.img-grid {
  display: grid;
  /* 固定2列,宽度均分 */
  grid-template-columns: repeat(2, 1fr);
  /* 图片间距可自行调整 */
  gap: 8px;
  width: 100%;
  margin-top: 8px;
}

/* 单张图片时占满整行 */
.img-grid img:first-child:nth-last-child(1) {
  grid-column: 1 / -1;
}

/* 图片样式,避免变形 */
.img-grid img {
  width: 100%;
  /* 单张图片固定高度,可自行调整 */
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

效果说明

  • 容器内无图片时:.img-grid 无高度,符合无图片的展示规则
  • 容器内1张图片:图片占满整行宽度,容器高度为单张图片高度
  • 容器内2张图片:两张图片各占50%宽度排在同一行,容器高度为单张图片高度
  • 容器内图片数量≥3时:grid自动生成新行放置超出的图片,容器高度自动向下扩展

内容的提问来源于stack exchange,提问作者Afdal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:48:03