:last-child 失效因表格末尾可能存在 tfoot、注释或空格等非 tr 子节点;应改用 tr:nth-last-child(1) 或 tbody tr:nth-last-child(1),或为统计行添加 class 如 tr.summary;若在 tfoot 中则用 tfoot tr:first-child。

为什么 :last-child 对表格统计行经常失效
直接给 <tr> 写 <code>tr:last-child { background: #eee; } 看似合理,但实际常没反应——因为 :last-child 匹配的是父元素中「最后一个子元素」,而表格里末尾可能有 <tfoot>、注释、空格文本节点,甚至被 JS 动态插入的隐藏行。只要它不是 DOM 树里 <code><tbody> 或 <code><table> 的最后一个直接子节点,就匹配不到。
<h3>用 <code>:nth-last-child(1) 替代更可靠
:nth-last-child(1) 和 :last-child 行为不同:前者只看「同类型兄弟元素」中的倒序位置,忽略文本节点和非 <tr> 元素。只要目标行是 <code><tr> 类型里的最后一个,就能稳稳命中。
<p>实操建议:</p>
<ul><li>确保统计行是 <code><tbody> 内最后一行(而非放在 <code><tfoot>),否则需调整选择器作用域
<li>写成 <code>tbody tr:nth-last-child(1) { font-weight: bold; background: #f5f5f5; }
class="summary"),优先用 tr.summary,语义更强、不依赖位置当统计行在 <tfoot> 里时怎么选
<p>若设计要求统计行必须放 <code><tfoot>(语义正确),<code>:last-child 反而可能生效,但前提是 <tfoot> 是 <code><table> 的最后一个子元素,且内部只有单个 <code><tr>。
<p>稳妥写法:</p>
<ul><li>
<code>tfoot tr:first-child —— 因为 <tfoot> 通常只含一行统计,用 <code>:first-child 更直白
tfoot > tr —— 若确定 <tfoot> 里没有嵌套表格或多余标签
<li>避免写 <code>table tr:last-child,它会跨 <thead>/<code><tbody>/<code><tfoot> 边界匹配,极易误伤
<h3>兼容性与样式穿透问题</h3>
<p>IE8 不支持 <code>:nth-last-child(),但 IE8 本身已基本退出主流场景;真要兼容,可加 JS 判断后添加 class:document.querySelector('tbody').lastElementChild.classList.add('summary-row');
另外注意:
- CSS 优先级可能被行内
style覆盖,必要时加!important(仅限调试) - 某些 UI 框架(如 Bootstrap Table)会重写
<tr> 结构,先检查渲染后的 DOM 是否仍是扁平 <code><tr> 序列 <li>用 <code>background-color突出时,记得同步设color,避免文字在浅灰背景上不可读
位置不是唯一依据,类型和上下文才决定伪类是否真正落地。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











