css極簡方法實現固定表頭table

通常的第三方庫都有現成的表格組件,支持固定表頭,當表格數據過多時,有滾動的效果。那麼如果讓我們自己實現一個類似的表格,應該怎麼實現呢?下面我就介紹一種極簡單的方式實現固定表頭可滾動表格。下面是html代碼:

<body>
    <!-- 實現一個固定表頭,可滾動的table -->
    <div>
      <table>
        <thead>
          <th>第一列</th>
          <th>第二列</th>
          <th>第三列</th>
        </thead>
        <tbody>
          <tr>
            <td>aaaa</td>
            <td>bbbb</td>
            <td>cccc</td>
          </tr>
          <tr>
            <td>aaaa</td>
            <td>bbbb</td>
            <td>cccc</td>
          </tr>
          <tr>
            <td>aaaa</td>
            <td>bbbb</td>
            <td>cccc</td>
          </tr>
          <tr>
            <td>aaaa</td>
            <td>bbbb</td>
            <td>cccc</td>
          </tr>
          <tr>
            <td>aaaa</td>
            <td>bbbb</td>
            <td>cccc</td>
          </tr>
          <tr>
            <td>aaaa</td>
            <td>bbbb</td>
            <td>cccc</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>

接下來我們添加一些樣式,使表格看起來不那麼難看

<style>
      /* 給容器一個寬度,並在頁面居中 */
      div {
        width: 500px;
        margin: 0 auto;
      }

      table {
        border-collapse: collapse;
        width: 100%;
        border: 1px solid gray;
        text-align: center;
      }
      table thead {
        background-color: orange;
      }
      table tbody tr:nth-of-type(even) {
        background-color: lightblue;
      }
</style>

現在你看到的表格應該是這樣的:

下面加上這段css,以實現滾動效果

      /* 使用最簡單的滾動方法,在y軸實現滾動效果 */
      table tbody {
        display: block;
        height: 100px;
        overflow-y: scroll;
      }

此時你看到的效果應該是下面這樣的:

我們發現有個問題,tbody的寬度變窄了,接下來我們來解決這個問題

      /* tr設置寬度,並採用table佈局 */
      table tr {
        width: 100%;
        display: table;
      }

再來看下效果

現在固定表頭的滾動效果已經實現了,但是還有點瑕疵,我們能不能把滾動條隱藏掉呢?加上下面這段css試試

      table tbody {
        /* firefox */
        scrollbar-width: none;
        /* ie10+ */
        -ms-overflow-style: none;
      }
      /* chrome safari */
      table tbody::-webkit-scrollbar {
        display: none;
      }

現在滾動條消失了,我們完美實現了固定表頭可滾動表格。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章