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

如何在CSS Grid中实现Non-conforming单元格/网格线

实现表格行内的「非顺应」CSS Grid单元格

嘿,我懂你想在表格行的CSS Grid布局里设置「非顺应」单元格的需求了——也就是让某些单元格不跟着统一的网格规则走,对吧?先把你没写完的代码补全,再给你完整的实现方案:

完整代码示例

HTML

<table>
  <tr>
    <td class="a"></td>
    <td class="b"></td>
    <td class="c"></td>
    <td class="d">Text</td>
    <td class="e"></td>
    <td class="f">
      <button>Btn</button>
    </td>
  </tr>
</table>

CSS

table {
  width: 100%;
  border-collapse: collapse; /* 消除表格默认间距干扰 */
}

tr {
  text-align: center;
  display: grid;
  height: 200px;
  /* 默认给前5个单元格设置均分网格列,预留第6个作为非顺应项 */
  grid-template-columns: repeat(5, 1fr);
  gap: 2px; /* 可选:添加单元格间距,更易区分 */
}

/* 让.f单元格打破网格规则,自适应内容宽度 */
td.f {
  grid-column: auto;
  width: fit-content;
  padding: 0 10px;
  align-self: center; /* 让按钮垂直居中 */
}

/* 给常规单元格加背景,方便直观看到布局效果 */
td.a, td.b, td.c, td.d, td.e {
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

核心实现思路

  • 我们给tr的grid-template-columns设置了5个均分的1fr列,而第6个单元格.f脱离这个规则,通过grid-column: auto让它自动占据内容所需的宽度,实现「非顺应」的效果。
  • 如果想要让某个单元格跨多列(比如让.d跨2列),可以这么写:
    td.d {
      grid-column: span 2;
    }
    
    这时候记得把tr的grid-template-columns调整为repeat(4, 1fr),保证总列数匹配即可。

注意要点

  • 把tr设为display: grid后,表格的原生对齐特性会被覆盖,所以需要手动用flex或者align-self来调整单元格内容的对齐方式。
  • CSS Grid在主流浏览器里兼容性很好,如果需要适配极旧浏览器,可以提前查一下兼容性表再调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:32:10