首页 >web前端 >css教程 >如何仅使用 CSS 在表格中创建固定标题和列?

如何仅使用 CSS 在表格中创建固定标题和列?

Susan Sarandon
Susan Sarandon原创
2024-12-08 09:08:111095浏览

How to Create a Fixed Header and Column in a Table Using Only CSS?

使用纯 CSS 固定表格中的标题和列

使用纯 CSS 创建具有固定标题和固定第一列的表格可以可以使用position:sticky属性来实现。这种方法比依赖 JavaScript 或 jQuery 的解决方案更高效且跨浏览器兼容。

解决方案:

  1. 包裹表格在容器中:

    `

    `
  2. 在容器上启用滚动:

    `div.container {
    溢出:滚动;
    }`

  3. 粘桌子标题:

    `标题{
    位置:-webkit-sticky; / 对于 Safari /
    位置:粘性;
    顶部:0;
    }`

  4. 粘第一列:

    `第 {
    位置: -webkit-粘性; / 对于 Safari /
    位置:粘性;
    左:0;
    }`

  5. 可选: 粘性左上角第一列的标题:

    `thead th:first-child {
    left: 0;
    z-index: 2;
    }`

附加说明:

  • 为了获得最佳性能,容器应具有最大宽度和高度
  • 如果第一列包含 ; elements 而不是 ,在 CSS 中使用 tbody td:first-child 而不是 tbody th。
  • 要进一步设置标题和第一列的样式,请根据需要调整 CSS 属性。
  • 示例:

    <div class="container">
      <table border="1">
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th>1</th>
            <td>John Doe</td>
            <td>john@example.com</td>
            <td>(555) 123-4567</td>
          </tr>
          <tr>
            <th>2</th>
            <td>Jane Smith</td>
            <td>jane@example.com</td>
            <td>(555) 234-5678</td>
          </tr>
          <!-- More rows... -->
        </tbody>
      </table>
    </div>
    div.container {
      max-width: 500px;
      max-height: 300px;
      overflow: scroll;
    }
    
    thead th {
      position: sticky;
      top: 0;
    }
    
    tbody th {
      position: sticky;
      left: 0;
    }
    
    thead th:first-child {
      left: 0;
      z-index: 2;
    }

以上是如何仅使用 CSS 在表格中创建固定标题和列?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn