如何为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
相关产品推荐
相关产品推荐

