css表格隔行高亮怎么写_使用nth child实现

11次阅读

用 nth-child 实现表格隔行高亮的关键是选中 tbody 内偶数或奇数 tr 并设背景色:tbody tr:nth-child(even) { background-color: #f5f5f5; } 或 tbody tr:nth-child(odd) { background-color: #eef7ff; },避免影响表头。

css表格隔行高亮怎么写_使用nth child实现

nth-child 实现表格隔行高亮,关键是选中偶数行或奇数行的 tr 元素,并为其设置背景色。

基础写法:偶数行高亮

最常用的是给偶数行(第2、4、6…行)加背景色:

table tr:nth-child(even) {   background-color: #f5f5f5; }

其中 even 等价于 2n,表示所有偶数位置的 tr

奇数行高亮(比如首行强调)

如果想高亮第1、3、5…行,用 odd2n+1

立即学习前端免费学习笔记(深入)”;

table tr:nth-child(odd) {   background-color: #eef7ff; }

注意:只作用于同级 tr,避开表头和脚注

如果表格含 theadtbody,直接写 tr:nth-child(even) 可能误选表头行。更稳妥的方式是限定在 tbody 内:

  • tbody tr:nth-child(even) —— 正确,只对数据行生效
  • table tr:nth-child(even) —— 可能连 thead > tr 一起高亮(取决于 html 结构)

推荐始终加上 tbody 限定,避免意外。

兼容性与替代方案

:nth-child() 在 IE9+ 及所有现代浏览器中都支持。如需兼容 IE8,可用 js 或为每行手动加 class(如 class="tuc-19bc10f7-5b0678-0 row-even tuc-19bc10f7-5b0678-0"),但已不推荐。

不复杂但容易忽略。

text=ZqhQzanResources