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

动态CSS Grid第二行高度未生效,请问配置存在什么问题?

动态网格行高度未生效问题解析

问题描述

我想要创建一个动态网格(dynamic grid),以下是我当前使用的CSS代码,请问为何设置的行高度没有应用到第二行?

我的CSS代码

.container{
    display: grid;
    grid-template-columns: repeat(auto-fill, 170px);
    grid-template-rows: repeat(auto-fill, 300px);
}

问题截图

网格行高异常截图

我的HTML代码

<div class="container">
   <div>
       css
   </div>
   <div>
      html
   </div> 
</div>

问题原因

grid-template-rows 不支持 auto-fill 关键字——这个属性仅适用于 grid-template-columns,用来根据容器宽度自动填充列数。在行方向上,浏览器无法通过 auto-fill 自动生成行规则,所以超出定义行的部分会 fallback 到网格项的内容高度,也就是默认自适应高度,这就导致第二行的300px高度设置不生效。

解决方案

如果想让所有行都保持固定高度,推荐以下两种方案:

方案1:使用 grid-auto-rows(适合动态行数场景)

通过grid-auto-rows指定自动生成的行的高度,不管后续有多少行,都会统一应用这个高度:

.container{
    display: grid;
    grid-template-columns: repeat(auto-fill, 170px);
    grid-auto-rows: 300px;
}

方案2:直接指定固定行数(适合已知行数场景)

如果能确定网格的行数,可以直接用repeat(N, 300px)定义行规则,比如固定2行:

.container{
    display: grid;
    grid-template-columns: repeat(auto-fill, 170px);
    grid-template-rows: repeat(2, 300px);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:50:22