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

如何在表格单元格内部或之间创建半高边框

实现表格半高竖线的解决方案

方法1:单元格之间的半高分隔竖线

通过CSS伪元素可精准控制竖线的高度与位置,不受单元格height属性影响,代码示例如下:

HTML结构

<table>
  <tr>
    <td>单元格1</td>
    <td>单元格2</td>
    <td>单元格3</td>
  </tr>
  <tr>
    <td>单元格4</td>
    <td>单元格5</td>
    <td>单元格6</td>
  </tr>
</table>

CSS样式

table {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
}
td {
  position: relative;
  padding: 0 20px;
  height: 80px; /* 自定义单元格高度 */
  line-height: 80px; /* 文本垂直居中 */
}
/* 为除第一个单元格外的所有单元格添加左侧半高竖线 */
td:not(:first-child)::before {
  content: "";
  position: absolute;
  left: 0;
  top: 25%; /* 竖线顶部距单元格顶部25% */
  height: 50%; /* 竖线高度为单元格高度的50% */
  width: 1px;
  background-color: #ccc; /* 竖线颜色 */
}

方法2:单元格内部的半高竖线

若需在单个单元格内添加半高分隔线,可结合Flex布局与伪元素实现:

HTML结构

<table>
  <tr>
    <td>
      <span>左侧内容</span>
      <span>右侧内容</span>
    </td>
    <td>单元格2</td>
  </tr>
</table>

CSS样式

table {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
}
td {
  position: relative;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}
/* 为单元格内除第一个span外的元素添加左侧半高竖线 */
td span:not(:first-child)::before {
  content: "";
  height: 50%;
  width: 1px;
  background-color: #ccc;
}

原方案失效原因

  • 基于line-height的方案依赖文本行高,当设置td或tr固定height后,文本行高与单元格高度脱离,导致竖线无法保持半高。
  • repeating-linear-gradient若未精准控制渐变起止位置与尺寸,易出现重复绘制或高度不符预期的问题,而伪元素可直接通过height和top属性精准控制竖线的位置与高度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:03:27