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

CSS subgrid元素溢出问题:网格容器未自适应致内容重叠

解决Grid容器未自适应导致内容溢出的问题

我看了你的代码,问题主要出在两个地方:强制固定的网格行高和列宽的minmax设置没有适配换行内容,再加上无空格长文本的换行规则需要更直接的生效路径。下面是具体的修复方案:

1. 移除网格行的强制100%高度

你的.grid类设置了grid-template-rows: 100%;,这会强制网格行只能占100%的高度,当内容换行后高度超过这个值时,就会直接溢出到下方的容器里。把这行删掉,让网格行自动根据内容高度调整:

.grid {
  display: grid;
  grid-template-columns: minmax(auto, 80%) auto;
  /* 删掉 grid-template-rows: 100%; */
}

2. 优化列宽设置以适配长文本换行

对于无空格的长文本,minmax(auto, 80%)里的auto可能无法正确计算换行后的宽度,导致列宽没有收缩到允许换行的范围。把auto改成0,让列能够在需要时收缩,配合overflow-wrap: break-word生效:

.grid {
  display: grid;
  grid-template-columns: minmax(0, 80%) auto;
}

3. 确保换行规则直接作用于长文本容器

虽然你给.container加了overflow-wrap: break-word,但最好把这个属性直接加到.col1里,确保长文本所在的直接容器应用换行规则,避免继承可能带来的意外:

.col1 {
  grid-column: 1;
  grid-row: 1;
  justify-self: left;
  align-self: start;
  overflow-wrap: break-word;
}

完整修复后的CSS代码

body {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.layout {
  width: 100%;
  display: grid;
  grid-template-columns: 20% 80%;
  box-sizing: border-box;
}

.left {
  width: 100%;
  grid-column: 1;
  box-sizing: border-box;
  word-wrap: break-word;
}

.right {
  width: 100%;
  grid-column: 2;
  box-sizing: border-box;
}

.container {
  box-sizing: border-box;
  margin-left: 4px;
  margin-right: 4px;
  padding-top: 4px;
  padding-bottom: 4px;
  border-bottom: 1px solid black;
  overflow-wrap: break-word;
}

.container:last-child {
  padding-bottom: 4px;
  border-bottom: none;
}

.grid {
  display: grid;
  grid-template-columns: minmax(0, 80%) auto;
}

.col1 {
  grid-column: 1;
  grid-row: 1;
  justify-self: left;
  align-self: start;
  overflow-wrap: break-word;
}

.col2 {
  grid-column: 2;
  grid-row: 1;
  justify-self: right;
  align-self: start;
}

修复原理说明

  • 去掉grid-template-rows: 100%后,网格行会根据内容的实际高度自动调整,不会再限制高度导致溢出。
  • minmax(0, 80%)让第一列最大占80%宽度,最小可以收缩到0(配合换行),这样无空格的长文本会在列宽范围内自动换行,而不会撑破网格容器。
  • 给.col1直接加overflow-wrap: break-word,确保长文本所在的直接容器应用换行规则,避免继承可能带来的问题。

这样修改后,每个.container.grid都会自适应内容高度,长文本会正确换行,不会再流入到第三个项目里了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:28:29