跳到主要內容

利用CSS設定表格首行&首列維持固定位置

【HTML】

<div>

     <table>

       <thead>

         <tr>

           <th>標題A</th>

           <th>標題B</th>

           <th>標題C</th>

           <th>標題D</th>

           <th>標題E</th>

         </tr>

       </thead>

       <tbody>

         <tr>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

         </tr>

         <tr>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

         </tr>

         <tr>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

           <td>內文</td>

         </tr>

      </tbody>

     </table>

</div>


【CSS語法】

div{ overflow:auto;  width:100%; height:181px; /* 固定高度 */}

td, th { /*這裡只是設定出表格欄位的樣式 */

 border:1px solid gray;

 width:100px;

 height:30px;

}

th { background-color:lightblue; }

table {margin:0 auto;

 table-layout: fixed;/* 表格的總寬度決定於表格 width 的定義,以及各欄位(Column) width 的定義 */

 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;

}


【說明&示意圖】

建立固定欄位,需在 table 和 th 各自設定以下兩個 CSS 屬性

  • table-layout : fixed  
  • position : sticky

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

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


點此觀看影片


參考資料來源:https://www.astralweb.com.tw/pure-css-implementation-table-headers-columns-fixed/