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

如何让3行2列网格的第一列宽度统一为最长文本宽度?

解决方案:统一Grid列宽适配最长文本

你的问题核心在于每个.tableRow都是独立的Grid容器,所以每行的列宽只会根据自身内容计算,导致第一列宽度不一致。要让所有行共享统一的列宽,需要把Grid布局的定义从.tableRow移到父容器.table上,具体修改如下:

修改后的CSS代码

/* 将Grid布局移到父容器.table,让所有行共享列轨道 */
.table {
  display: grid;
  grid-template-columns: max-content 1fr;
  border: 1px solid #000;
}

.tableRow {
  position: relative;
  text-decoration: none;
  color: inherit;
  border-bottom: 1px solid #000;
}
/* 移除最后一行的下边框 */
.tableRow:last-child {
  border-bottom: none;
}

.tableRow:hover, .tableRow:focus {
  background: #eee;
  outline: none;
}

.tableRow a:not(.tableRowLink) {
  position: relative;
  z-index: 1;
}

.tableCell {
  padding: 18px;
  border-right: 1px solid #000;
  align-content: center;
  display: flex;
  align-items: center;
}
.tableCell:last-of-type {
  border-right: none;
}

.tableRowLink {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

修改后的HTML结构(无需改动,保持原结构即可)

<div class="table">
  <div class="tableRow">
    <div class="tableCell"><a href="#" target="_blank"><p>Link.com</p></a></div>
    <div class="tableCell"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div>
    <a class="tableRowLink" href="#" target="_blank"></a>
  </div>
  <div class="tableRow">
      <div class="tableCell"><a href="#" target="_blank"><p>Link-Link.com</p></a></div>
      <div class="tableCell"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div>
      <a class="tableRowLink" href="#" target="_blank"></a>
    </div>
    <div class="tableRow">
      <div class="tableCell"><a href="#" target="_blank"><p>Link-Link-Link.com</p></a></div>
      <div class="tableCell"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div>
      <a class="tableRowLink" href="#" target="_blank"></a>
    </div>
</div>

原理说明

  • 将display: grid和grid-template-columns: max-content 1fr放到父容器.table后,整个表格成为单一Grid容器,所有.tableRow作为Grid项目自动对齐到统一的列轨道,第一列会根据所有行中最长的文本自动调整宽度。
  • max-content确保第一列仅适配最长文本的宽度,1fr让第二列占据剩余所有空间,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:53:10