首页 文章

在具有预设背景颜色的表中悬停时更改背景颜色

提问于
浏览
0

我正在尝试使用CSS和 :hover 更改整个tbody的背景颜色 . 如果已经设置了背景,我无法更改悬停背景 . 我根本不能 . 我甚至试过 !impotant 但没有运气 .

<table border="1">
    <tbody>
    <tr>
        <th>Testing</th>
        <td>Some stuff</td>
    </tr>
    <tr>
        <th>Testing</th>
        <td>Second more stuff</td>
    </tr>
    </tbody>
</table>

My CSS

th {
    background: red;
}
tbody:hover {
    background: blue !important;
}

http://jsfiddle.net/W4cJh/1/

如您所见,如果尚未设置背景,则悬停可以正常工作 . 从th-tag中删除 background: red ,看它是否在没有预设颜色的情况下工作 .

2 回答

  • 1

    那是因为 TH 是表的子项,因此技术上也是如此 . 通过将 TABLE 背景设置为蓝色,它不会覆盖 TH 背景 .

    要解决此问题,请添加:

    tbody:hover th {
      background: blue;
    }
    

    (你可以跳过 !important s . 这些都是不好的做法 . )

    Example fiddle is here.

  • 2

    这将为您完成工作,不需要 !important

    th {
        background: red;
    }
    tbody:hover,
    tbody:hover th {
        background: blue;
    }
    

    Demo: http://jsfiddle.net/W4cJh/4/

相关问题