CSS实现:固定Table表头和第一列

1,165 阅读2分钟

当表格内容太多的时候,固定表头不让标题滚出屏幕外,是一个很人性化的设计;而当横向项目内容太多时,固定第一列(项目列)也是一个很贴心的设计。本文介绍如何用CSS实现固定Table表头和第一列。

202106300510475886.gif

CSS

  table {
    font-family"Fraunces", serif;
    font-size125%;
    white-space: nowrap;
    margin0;
    border: none;
    border-collapse: separate;
    border-spacing0;
    table-layout: fixed;
    border1px solid black;
  }
  table td,
  table th {
    border1px solid black;
    padding0.5rem 1rem;
  }
  table thead th {
    padding3px;
    position: sticky;
    top0;
    z-index1;
    width25vw;
    background: white;
  }
  table td {
    background#fff;
    padding4px 5px;
    text-align: center;
  }
   
  table tbody th {
    font-weight100;
    font-style: italic;
    text-align: left;
    position: relative;
  }
  table thead th:first-child {
    position: sticky;
    left0;
    z-index2;
  }
  table tbody th {
    position: sticky;
    left0;
    background: white;
    z-index1;
  }
  caption {
    text-align: left;
    padding0.25rem;
    position: sticky;
    left0;
  }
   
  [role="region"][aria-labelledby][tabindex] {
    width450px;
    height400px;
    overflow: auto;
    box-shadow0 0 0.8em rgba(0000.5);
    outline0;
  }

HTML

<div role="region" aria-labelledby="caption" tabindex="0">
  <table>
    <caption id="caption">棒球号码</caption>
    <thead>
      <tr>
        <th>Teams</th>
        <th>1</th>
        <th>2</th>
        <th>3</th>
        <th>4</th>
        <th>5</th>
        <th>6</th>
        <th>7</th>
        <th>8</th>
        <th>9</th>
        <th>Runs</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th>Milwaukee Brewers</th>
        <td>2</td>
        <td>0</td>
        <td>4</td>
        <td>1</td>
        <td>0</td>
        <td>3</td>
        <td>0</td>
        <td>3</td>
        <td>4</td>
        <td>17</td>
      </tr>
      <tr>
        <th>Los Angles Dodgers</th>
        <td>0</td>
        <td>2</td>
        <td>3</td>
        <td>1</td>
        <td>3</td>
        <td>4</td>
        <td>3</td>
        <td>2</td>
        <td>4</td>
        <td>22</td>
      </tr>
    </tbody>
  </table>
</div>

代码解释

这里的“技巧”部分是position: sticky;用法,但更重要的是你必须知道如何处理重叠元素。

固定表格单元格需要有背景,否则我们会看到重叠的内容。它还需要适当的z-index处理,以便当它固定到位时,它会位于它应该位于的顶部。这感觉是最棘手的部分:

  • 确保tbody>th单元格位于常规表格单元格上方,以便它们在水平滚动期间保持在顶部。
  • 确保thead>th单元格在这些单元格之上,以便垂直滚动。
  • 确保thead>th:first-child单元格是最高的,因为它需要位于正文单元格上方,并且它又是水平滚动的同级标题。

只固定Table表头

如果只想固定Table表头,那么很简单,我们只需把前面的HTML代码<th>...</th>这列即是第一列去掉即可。