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

如何设置CSS Grid行高以实现根据内容自动调整?

解决CSS Grid行高无法自适应内容的问题

你当前的布局存在两个核心问题:

  1. 手动指定grid-template-rows: auto auto后,Grid会强制分配两行的高度,而跨两行的item-1会被限制在这两行的总高度内,内容过多时直接溢出
  2. state-info和pan-info的flex布局未设置换行,横向内容超出容器宽度时会溢出

修改后的CSS代码

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

@page {
  size: A4;
  margin: 0.8cm;
  border: 1px solid #000;
  @bottom-right {
    content: counter(page) " / " counter(pages);
    font-size: 10px;
    color: black;
  }
}

html,
body {
  height: 100%;
  width: 100%;
}

.big {
  font-size: 14px;
}

p {
  font-size: 10px;
}

.section-3 {
  word-break: break-all;
}

.section-3-body {
  display: grid;
  grid-template-columns: 65% 17.5% 17.5%;
  /* 移除手动指定的行高,让Grid根据内容自动计算行高 */
  border-bottom: 1px solid black;
}

.state-info,
.pan-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  /* 添加换行规则,避免横向内容溢出 */
  flex-wrap: wrap;
  gap: 8px; /* 可选,添加间距优化排版 */
}

.item-1 {
  grid-column: 1/2;
  grid-row: 1 / span 2;
  border-right: 1px solid black;
  padding: 4px; /* 可选,添加内边距避免文字紧贴边框 */
}

.item-2 {
  grid-column: 2 / 4;
  grid-row: 1 / 2;
  border-bottom: 1px solid black;
  text-align: center;
  padding: 4px;
}

.item-3 {
  grid-column: 2/3;
  grid-row: 2 / 3;
  border-right: 1px solid black;
  text-align: center;
  padding: 4px;
}

.item-4 {
  grid-column: 3/4;
  grid-row: 2 / 3;
  text-align: center;
  padding: 4px;
}

修改说明

  • 移除grid-template-rows的手动设置后,Grid会根据item-1的内容高度自动调整两行的总高度,彻底解决内容溢出问题
  • 给state-info和pan-info添加flex-wrap: wrap,让内部元素在宽度不足时自动换行,避免横向溢出
  • 可选添加内边距和间距,优化内容与边框的距离,提升排版美观度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 23:44:56