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

如何为HTML表格<td>元素设置垂直方向背景色?

实现表格垂直列(纵向)背景色设置

嗨,看你已经搞定了表格的行背景色,要改成垂直列的样式其实很简单,只需要把选择器从**行(tr)换成对应列的单元格(td/th)**就行啦!

原来的代码是针对奇数行设置背景:

table tr:nth-child(2n-1) td { background: #F5F5F5; }

要实现纵向列的背景色,我们直接针对单元格的列位置来选择,把选择器改成td:nth-child(2n-1)(如果需要表头th同步样式,就加上th:nth-child(2n-1)):

修改后的完整CSS代码

table { 
  width: 100%; 
  border-collapse: collapse; 
  border-spacing: 0; 
  margin-bottom: 20px; 
} 
/* 给奇数列设置背景色 */
table td:nth-child(2n-1), 
table th:nth-child(2n-1) { 
  background: #F5F5F5; 
} 
table th, table td { 
  text-align: center; 
} 
table th { 
  padding: 5px 20px; 
  color: #5D6975; 
  border-bottom: 1px solid #C1CED9; 
  white-space: nowrap; 
  font-weight: bold; /* 补全你未写完的font-weight属性 */
}

小提示

  • 如果想给偶数列设置背景色,把2n-1换成2n即可
  • 加上th:nth-child()是为了让表头和内容列的背景色保持统一,要是不需要表头变色,只保留td的选择器就好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:16:57