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

CSS Grid动态卡片布局咨询:最后一行卡片自适应占满宽度

问题

使用grid-template-columns: repeat(3, minmax(200px, 1fr))实现每行3张的卡片布局,现有5张卡片时,希望最后一行的2张卡片平分该行宽度;若只剩1张卡片则占满整行。由于卡片从API动态获取,无法确定最后剩余数量,不能直接用固定的nth-of-type定位,该如何处理?

原代码如下:

CSS

body {
  max-width: 1440px;
  display: grid;
  grid-template-columns: repeat(3, minmax(200px, 1fr));
  gap: 1rem;
}

.card {
  height: 250px;
  background-color: orange;
}

HTML

<body>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
</body>

期望效果:
期望布局效果

解决方案

方法1:用伪类动态匹配末尾元素(简单直接)

无需修改基础Grid列配置,通过CSS伪类精准定位最后1个或2个卡片,调整它们的列跨度:

body {
  max-width: 1440px;
  display: grid;
  grid-template-columns: repeat(3, minmax(200px, 1fr));
  gap: 1rem;
}

.card {
  height: 250px;
  background-color: orange;
}

/* 最后只剩1张卡片时,占满整行 */
.card:nth-last-child(1):nth-child(3n + 1) {
  grid-column: span 3;
}

/* 最后剩2张卡片时,平分该行 */
.card:nth-last-child(2):nth-child(3n + 1) ~ .card {
  grid-column: span 1.5;
}

原理:

  • :nth-last-child(1):nth-child(3n + 1):匹配既是每行第1个位置(3n+1)又是倒数第1个的卡片,说明最后一行只有1张,让它跨3列填满整行。
  • :nth-last-child(2):nth-child(3n + 1) ~ .card:当倒数第2个卡片处于每行第1个位置时,说明最后一行有2张,让这两张各跨1.5列(3列总宽度刚好被平分)。

方法2:自适应列数+媒体查询(适配多屏幕)

如果需要在小屏幕上自动减少列数,可改用auto-fit配合动态列宽,再通过媒体查询处理最后一行:

body {
  max-width: 1440px;
  display: grid;
  /* 限制每行最多3张,同时支持小屏幕自动换行 */
  grid-template-columns: repeat(auto-fit, minmax(200px, calc((100% - 2*1rem)/3)));
  gap: 1rem;
  justify-content: center;
}

.card {
  height: 250px;
  background-color: orange;
}

/* 仅在宽度足够放下2张卡片时,处理最后一行 */
@media (min-width: calc(200px*2 + 1rem)) {
  /* 最后1张占满整行 */
  .card:nth-last-child(1):nth-child(3n + 1) {
    grid-column: 1 / -1;
  }
  /* 最后2张平分宽度 */
  .card:nth-last-child(2):nth-child(3n + 1) ~ .card {
    width: calc((100% - 1rem)/2);
  }
}

这个方法兼顾了大屏固定3列、小屏幕自适应的需求,同时保持最后一行的期望布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:32:41