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

如何用单个CSS Grid实现两组各占50%的左对齐列组(适配多行表格)

单个CSS Grid实现分两组的表格式布局需求

核心需求

  • 将6列的CSS Grid拆分为两组各3列的列组,每组占据父容器50%宽度,且内部左对齐
  • 每组内的单元格以min-content自适应内容宽度,同时限制在50%的组宽度内
  • 实际为Angular组件场景,通过*ngFor动态生成元素,总行数不确定,但每组固定3个单元格
  • 必须用单个Grid实现,避免嵌套div方案导致的不同行列无法对齐问题

现有无效代码

#parent {
  width: 100%;
  display: grid;
  grid-template-rows: 1fr;
  grid-template-columns: repeat(3, 1fr) repeat(3, 1fr);
}

.cell {
  background-color: yellow;
}

.cell2 {
  background-color: lightblue;
}
<div id="parent">
  <div class="cell">Label 1</div>
  <div class="cell">60</div>
  <div class="cell">44</div>
  <div class="cell2">Label 2 (xxxx)</div>
  <div class="cell2">80</div>
  <div class="cell2">11</div>
</div>

不可用的嵌套div方案(列无法对齐)

该方案会导致不同行的对应列无法像表格一样对齐,代码示例:

<div id="parent">
  <!-- first row -->
  <div class="cell cell1">
    <div>Label 1</div>
    <div>60</div>
    <div>44</div>
  </div>
  <div class="cell cell2">
    <div>Label 2 (xxxx)</div>
    <div>80</div>
    <div>11</div>
  </div>

  <!-- second row -->
  <div class="cell cell1">
    <div>Label3 xxx</div>
    <div>60</div>
    <div>44</div>
  </div>
  <div class="cell cell1">
    <div>Label4 1xxx</div>
    <div>60</div>
    <div>44</div>
  </div>
</div>
#parent {
  width: 100%;
  display: grid;
  grid-template-rows: 1fr;
  grid-template-columns: 1fr 1fr;
}

.cell {
  display: flex;
  gap: 1rem; 
}

.cell1{
  background-color: yellow;
}

.cell2 {
  background-color: lightblue;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:05:42