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

CSS表格tr:hover选择器对含th的首行tr不生效问题求助

CSS表格首行tr:hover背景色不生效的原因及解决方法

问题描述

查看W3Schools的CSS表格代码时发现,#customers tr:hover选择器设置的#ddd背景色,对包含<th>元素、背景为绿色的首行<tr>不生效。原本预期所有<tr>元素在鼠标悬停时都会显示该背景色,想知道是否对首行<tr>存在特殊限制?

相关代码如下:

CSS代码

#customers {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

#customers td,
#customers th {
  border: 1px solid #ddd;
  padding: 8px;
}

#customers tr:nth-child(even) {
  background-color: #f2f2f2;
}

#customers tr:hover {
  background-color: #ddd;
}

#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #04aa6d;
  color: white;
}

HTML代码

<h1>A Fancy Table</h1>

<table id="customers">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbköp</td>
    <td>Christina Berglund</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Königlich Essen</td>
    <td>Philip Cramer</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>Simon Crowther</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris spécialités</td>
    <td>Marie Bertrand</td>
    <td>France</td>
  </tr>
</table>

原因分析

这不是首行<tr>的特殊限制,而是子元素样式覆盖父元素的问题:

  • 首行的<tr>其实已经触发了tr:hover的背景色,但它内部的<th>元素被直接设置了background-color: #04aa6d
  • <th>是<tr>的子元素,子元素的背景色会直接覆盖父元素<tr>的背景色,所以你看不到<tr>的hover效果

解决方法

方法1:给hover状态的单独设置背景色

直接给悬停时的<th>设置和<tr>一致的背景色,覆盖原来的绿色:

#customers tr:hover th {
  background-color: #ddd;
}

把这段代码加到原有CSS中,当鼠标悬停在首行时,<th>的背景色会变成#ddd,和其他行的hover效果统一。

方法2:把首行背景色移到上

修改原有CSS,将<th>的背景色转移到首行<tr>上,这样<tr>的hover样式就能直接覆盖默认背景色:

/* 替换原来的#customers th中的background-color */
#customers tr:first-child {
  background-color: #04aa6d;
}

#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  color: white; /* 保留文字颜色,去掉background-color */
}

这种方式下,<tr>的默认背景色和hover背景色都作用在同一个元素上,hover状态的样式会优先生效。


内容的提问来源于stack exchange,提问作者Ramez Soliman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:02:29