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

CSS Grid实现列宽等于列内内容最大宽度的布局问题

解决方案

需求回顾

  • 容器宽度足够时,所有项单行排列,列宽等于对应文本宽度
  • 宽度不足时自动换行,每列宽度为该列所有内容的max-content
  • 列内文本左对齐

问题分析

原代码中grid-template-columns: repeat(auto-fill, minmax(max-content, 0px))存在参数顺序错误(minmax需先写最小值、后写最大值),导致浏览器解析为固定max-content列宽,无法根据容器宽度自动调整列数,最终引发溢出且无法换行。同时grid-template-rows使用auto-fill属于误用,应改为自动行高配置。

修正后代码

HTML结构

<div class="container">
  <div class="item">Long text 01 </div>
  <div class="item">Item 2</div>
  <div class="item">Align with 1</div>
  <div class="item">Align with 1 </div>
  <div class="item">Item 5</div>
  <div class="item">Item 6</div>
</div>

CSS代码

.container {
  display: grid;
  grid-gap: 10px;
  /* 自动适配列数,列宽最小0、最大为内容宽度 */
  grid-template-columns: repeat(auto-fit, minmax(0, max-content));
  /* 自动设置行高为40px,也可改为auto自适应内容 */
  grid-auto-rows: 40px;
  width: 200px;
}

.item {
  border: 1px solid black;
  padding: 10px;
  /* 明确左对齐,默认已为左对齐,可省略 */
  text-align: left;
}

说明

  • repeat(auto-fit, minmax(0, max-content)):auto-fit会根据容器宽度自动创建足够的列,当容器宽度足够时,列数等于项目数,每个列宽为对应文本的max-content;当容器宽度不足时,自动减少列数并换行,此时每列宽度为该列所有项目的max-content。
  • grid-auto-rows: 40px:统一设置每行高度为40px,若不需要固定行高,可改为auto让行高自适应内容。
  • 文本左对齐为浏览器默认样式,若需明确可保留text-align: left。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:30:06