CSS 如何在 Bootstrap 3 中固定表头(thead)并同时在滚动表格行时将表头粘在顶部

在本文中,我们将介绍如何使用 CSS 在 Bootstrap 3 中实现固定表头(thead),同时在滚动表格行时使表头始终粘在页面顶部。

阅读更多:CSS 教程

1. CSS 定位技术

要实现固定表头效果,我们可以使用 CSS 中的定位技术。具体来说,我们可以使用 position: sticky; 属性来实现。

thead {
  position: sticky;
  top: 0;
  background-color: #fff;
}

上述代码将表头(thead)定位在页面顶部,并设置了背景色为白色。

2. HTML 结构

在应用上述 CSS 样式之前,我们需要按照以下 HTML 结构组织表格和表头。

<div class="table-responsive">
  <table class="table">
    <thead>
      <!-- 表头内容 -->
    </thead>
    <tbody>
      <!-- 表格行数据 -->
    </tbody>
  </table>
</div>

请确保在外层包裹了一个 .table-responsive 类,以便在表格过长时自动添加滚动条。

3. Bootstrap 运行示例

接下来,让我们通过一个具体的示例来演示如何在 Bootstrap 3 中固定表头。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
    thead {
      position: sticky;
      top: 0;
      background-color: #fff;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>邮箱</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>张三</td>
            <td>25</td>
            <td>[email protected]</td>
          </tr>
          <tr>
            <td>2</td>
            <td>李四</td>
            <td>30</td>
            <td>[email protected]</td>
          </tr>
          <!-- 更多表格行数据 -->
        </tbody>
      </table>
    </div>
  </div>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>

通过将上述示例代码保存为 HTML 文件并在浏览器中打开,您将看到具有固定表头效果的表格。

4. CSS 兼容性

需要注意的是,position: sticky; 属性的兼容性可能会受到一些限制。在某些较旧的浏览器或移动设备上可能不支持此属性。因此,在应用此解决方案之前,请确保您的目标用户及浏览器环境都能够良好地支持 position: sticky; 属性。

总结

通过使用 CSS 中的 position: sticky; 属性,我们可以很容易地实现在 Bootstrap 3 中固定表头的效果。只需为表头元素添加相应的 CSS 样式,即可在滚动表格行时保持表头始终粘在页面顶部。请记住,在应用此解决方案之前,先确保您的目标平台都对 position: sticky; 属性有良好的兼容性支持。

最后修改:2024 年 05 月 31 日
如果觉得我的文章对你有用,请随意赞赏