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

Bootstrap 4:如何实现带深色表头的可悬停表格(无需手动样式)

问题解答

这是Bootstrap 4的标准行为吗?

是。table-hover的默认样式会对表格内所有<tr>元素生效,包括<thead>里的表头行。当你给<thead>加table-dark时,只是给表头添加了深色背景,但并没有排除它的悬停样式,所以表头行依然会触发悬停效果。

怎么实现带深色表头的可悬停表格(不用手动加bg-dark text-light)?

用Bootstrap 4官方提供的thead-dark类就行,这是专门为深色表头设计的类,配合table-hover使用时,只会让<tbody>里的行触发悬停效果,表头不会受影响,完全符合需求。

修正后的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>Admin Page</title>
</head>
<body>
<div class="container">
    <div class="row">
        <table class="table table-hover text-center">
                  <thead class="thead-dark">
                        <tr>
                            <th scope="col">Name</th>
                            <th scope="col">Last name</th>
                            <th scope="col">Department</th>
                        </tr>
                  </thead>
                  <tbody>
                        <tr>
                            <td>John</td>
                            <td>Doe</td>
                            <td>IT</td>
                        </tr>
                        <tr>
                            <td>Jane</td>
                            <td>Doe</td>
                            <td>HR</td>
                        </tr>
                 </tbody>
          </table>
      </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

关于给thead tr加table-dark的奇怪效果

table-dark类是用来给整个表格(或单行)设置深色主题的,它自带了一套包括悬停状态在内的样式。当你给表头行单独加这个类时,会和table-hover的样式产生冲突,导致出现不符合预期的视觉效果,所以不推荐这么用。

内容的提问来源于stack exchange,提问作者Sergey Zolotarev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:37:19