
通过CSS选择器可以轻松为表格中的特殊行添加样式,比如奇数行、偶数行、第一行、最后一行或特定位置的行。以下是常用方法和示例。
1. 选中奇数行和偶数行(斑马条纹)
使用 :nth-child(odd) 和 :nth-child(even) 可以为表格的奇偶行设置不同背景色,提升可读性。
tr:nth-child(odd) {
background-color: #f9f9f9;
}
tr:nth-child(even) {
background-color: #eef6ff;
}
2. 选中第一行或最后一行
使用 :first-child 或 :last-child 可以单独设置表头或末尾行的样式。
tr:first-child {
font-weight: bold;
background-color: #003366;
color: white;
}
tr:last-child {
border-top: 2px solid #ccc;
}
3. 选中指定位置的行
使用 :nth-child(n) 可以精确控制某一行。例如,设置第3行背景为黄色:
立即学习“前端免费学习笔记(深入)”;
tr:nth-child(3) {
background-color: yellow;
}
也可以使用公式,如 n+4 表示从第4行开始的所有行:
tr:nth-child(n+4) {
color: gray;
}
4. 排除表头行后设置数据行样式
如果表格使用了 基本上就这些常见用法。合理使用CSS选择器能让你的表格更清晰美观,不需要额外的class或JavaScript。关键在于理解结构和伪类的匹配逻辑。 和 ,可以直接对
tbody tr 操作,避免影响表头。
tbody tr:nth-child(odd) {
background-color: #f0f8ff;
}










