需要用到的2个属性
table-layout : fixed
position : sticky
table-layout
table-layout属性有两种特定值:
- auto(预设值)-表格的总宽度决定每一个储存格(cell)的最大值
- 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 cellspacing="0" >
<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>