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

如何让不同宽度的CSS Grid元素在宽度不足时自动占满整行堆叠

解决方案

修改思路

  • 原代码的grid-template-columns: repeat(auto-fit, minmax(100px, 1fr))会强制列最小宽度100px且剩余宽度均分,无法适配内容实际宽度,改为以min-content为最小值,保证宽度足够时列宽贴合内容。
  • 给需要避免内容折行的区块添加white-space: nowrap规则,防止内容被挤压换行。
  • 调整secondItem的grid规则,使其内部子元素也能自动适配宽度,窄屏时自动堆叠。
  • 移除无意义的.grid>div:first-child规则(你的HTML中无.grid类,该规则未生效)。

修改后完整CSS代码

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-content, 1fr));
  text-align: center;
}

.firstItem {
  background: yellow;
  white-space: nowrap; /* 内容不折行 */
  padding: 8px;
}

.option {
  height: 100%;
  min-height: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap; /* 选项内容不折行 */
}

.secondItem {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-content, 1fr));
}

.optionsContainer {
  background-color: grey;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.check {
  background-color: pink;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
  white-space: nowrap; /* 复选框文字不折行 */
}

效果说明

  • 容器宽度充足时:黄色顶部区块、灰色选项区、粉色复选框区都会按照自身内容所需的最小宽度展示,所有文字不会折行、不会被挤压。
  • 容器宽度不足时:所有区块会自动垂直换行,每个区块都占满100%的容器宽度。

HTML代码无需修改,直接沿用你现有的代码即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:39:02