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: 500px;
            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>

 效果展示如下图

功能效果

 

posted @ 2020-09-01 14:34  燃燃的大尾巴  阅读(3454)  评论(0编辑  收藏  举报