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

实现两列布局表格:第二列可滚动且宽度匹配最长行

解决两列布局中第二列宽度未匹配最长行的问题(附Grid替代方案)

你的问题核心是第二列(.c2)被固定了width:200px,导致内部子元素无法跟随最长的.longest行(绿色单元格所在行)自动扩展宽度。下面提供两种解决思路:

一、修复现有Flex布局

只需要调整.c2的宽度设置,让它由内部最长内容撑开,同时确保子元素继承这个宽度:

修改后的CSS:

.c1 {
  width: 200px;
  height: 10rem;
  background-color: yellow;
}

.c2 {
  /* 移除固定width,让内容决定宽度 */
  background-color: cyan;
  overflow: scroll;
  display: flex; /* 替换inline-flex为flex,不影响布局 */
  flex-direction: column;
  align-items: stretch; /* 确保子元素撑满容器宽度,默认值可省略,但显式写更清晰 */
}

/* 保留该设置,确保子元素占满容器宽度 */
.c2 > div {
  width: 100%;
}

.outer {
  display: flex;
}

div {
  background-color: pink;
  border: 1px solid black;
}

.longest {
  display: flex;
  max-height: 20px;
}

.measure {
  width: 403px;
}

body {
  font-size: 20px;
}

.box {
  background-color: green;
  min-width: 50px;
}

HTML无需修改,调整后.c2会被.longest里的绿色单元格撑开宽度,其他粉色子元素也会自动匹配这个宽度。

二、改用Grid布局实现

Grid布局更适合这种行列对齐的场景,代码逻辑更直观:

完整代码如下:

.c1 {
  width: 200px;
  height: 10rem;
  background-color: yellow;
}

.c2 {
  background-color: cyan;
  overflow: scroll;
  display: flex;
  flex-direction: column;
}

.c2 > div {
  width: 100%;
}

.outer {
  display: grid;
  /* 第一列固定200px,第二列自适应内容宽度 */
  grid-template-columns: 200px auto;
  gap: 0; /* 可选,控制列间距 */
}

div {
  background-color: pink;
  border: 1px solid black;
}

.longest {
  display: flex;
  max-height: 20px;
}

.measure {
  width: 403px;
}

body {
  font-size: 20px;
}

.box {
  background-color: green;
  min-width: 50px;
}
<div class="outer">
  <div class="c1">
    left
    <div>products</div>
    <div> title 1</div>
    <div>title 2</div>
  </div>
  
  <div class="c2">
    <div class="longest">
      <div class="box">h</div>
      <div class="box">h</div>
      <div class="box">h</div>
      <div class="box">h</div>
      <div class="box">j</div>
    </div>
    <div>empty</div>
    <div>empty</div>
    <div> filter</div>
  </div>
</div>

<div class="measure">sasd</div>

Grid方案中,grid-template-columns: 200px auto直接定义了两列的宽度规则,第二列会自动匹配内部最长内容的宽度,同时.c2内部的Flex列布局保持子元素垂直排列,粉色单元格自然继承父容器宽度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:59:57