1. 程式人生 > 實用技巧 >純CSS實現表格首行和首列固定

純CSS實現表格首行和首列固定

Table表格 是 HTML 中常見的元素,現在為大家介紹存CSS實現固定行列

建立固定定位,我們會使用到二鍾特定的CSS屬性

  • table-layout : fixed
  • position : sticky

Table-layout

table-layout屬性有兩種特定值:

  1. auto(預設值)-表格的總寬度決定每一個儲存格(cell)的最大值
  2. fixed - 表格的總寬度決定於表格width的定義,以及各欄位(column)width的定義

為了讓表格呈現滾動效果,必須設定table-layout:fixed 並且給與表格寬度。

table {
 table-layout: fixed
; width: 100%; }

Position

大家對position 的作用應該不陌生,而固定表格則需要使用到position : sticky 的設定

sticky 的表現類似於relative 和fixed 的合體,在目標區域中可見時,他的行為就像relative 不會有任何變化,而當頁面滾動超出目標區域時,他的表現改為fixed會固定於目標位置

要注意的是當position:sticky應用於table,只能作用於<th>和<td>,並且一定要定義目標位置left/right/top/bottom 才會出現固定效果!

thead tr th {
 position
:sticky; top:0; }

說完這兩種屬性後,我們來實現一個可固定首行首列的表格

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>純CSS實現表格首行和首列固定</title>
    <!-- 插入Vue -->
    <script 
src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style> .main{ width: 100%; overflow:auto; height:208px; /* 設定固定高度 */ } td, th { /* 設定td,th寬度高度 */ border:1px solid gray; width:100px; height:30px; } th { background-color:lightblue; } table { table-layout: fixed; width: 200px; /* 固定寬度 */ } td:first-child, th:first-child { position:sticky; left:0; /* 首行永遠固定在左側 */ z-index:1; background-color:lightpink; } thead tr th { position:sticky; top:0; /* 列首永遠固定在頭部 */ } th:first-child{ z-index:2; background-color:lightblue; } </style> </head> <body> <div id="app"> <div class="main"> <table> <thead> <tr> <th> </th> <th> </th> <th> </th> <th> </th> <th> </th> <th> </th> <th> </th> <th> </th> <th> </th> </tr> </thead> <tbody> <tr v-for="(item, index) in 30" :key="index"> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </tbody> </table> </div> </div> </body> <script> var app = new Vue({ el: '#app', data: { message: 'Hello' }, }) </script> </html>

效果展示如下圖