纯CSS实现复杂表头和多列同时固定
在项目开发过程中,遇到需要固定表头和左侧列的情况,查了很多资料,网上有的给的是两表格进行固定,要计算两个表格每一行的高度,非常复杂。于是参考了一些网上的资料,动手写了一个复杂表头和多列同时固定的Demo,废话不多说,直接上代码:
DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>纯css实现表格多行多列固定title>
<style>
.main {
width: 800px;
overflow: auto;
height: 208px; /* 设置固定高度 */
}
td, th {
/* 设置td,th宽度高度 */
border: 1px solid gray;
width: 150px;
height: 30px;
background-color: white;
}
table {
table-layout: fixed;
width: 200px; /* 固定宽度 */
}
/*设置列固定*/
td:first-child, th:first-child {
position: sticky;
left: 0; /* 首行永远固定在左侧 */
}
td:nth-child(2), th:nth-child(2) {
position: sticky;
left: 150px; /* 首行永远固定在左侧 */
}
td:nth-child(3), th:nth-child(3) {
position: sticky;
left: 300px; /* 首行永远固定在左侧 */
}
/*设置行固定*/
thead tr:first-child th {
position: sticky;
top: 0;
}
thead tr:nth-child(2) th {
position: sticky;
top: 34px;
}
/*左侧th浮在最上层*/
th:first-child,th:nth-child(2),th:nth-child(3) {
z-index: 3;
}
/*通过第二行的th固定确定右侧th的层次*/
thead tr:nth-child(2) th {
z-index: 2;
}
style>
head>
<body>
<div id="app">
<div class="main">
<table cellspacing="0">
<thead>
<tr>
<th rowspan="2">标题1th>
<th rowspan="2">标题2th>
<th rowspan="2">标题3th>
<th colspan="2">标题4th>
<th colspan="2">标题5th>
<th colspan="2">标题6th>
tr>
<tr>
<th>标题4_1th>
<th>标题4_2th>
<th>标题5_1th>
<th>标题5_2th>
<th>标题6_1th>
<th>标题6_2th>
tr>
thead>
<tbody>
<tr v-for="(item, index) in 30" key="index">
<td>行1td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
<tr v-for="(item, index) in 30" key="index">
<td>行2td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
<tr v-for="(item, index) in 30" key="index">
<td>行3td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
<tr v-for="(item, index) in 30" key="index">
<td>行4td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
<tr v-for="(item, index) in 30" key="index">
<td>行5td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
<tr v-for="(item, index) in 30" key="index">
<td>行6td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
<tr v-for="(item, index) in 30" key="index">
<td>行7td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
<tr v-for="(item, index) in 30" key="index">
<td>行8td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
<td> td>
tr>
tbody>
table>
div>
div>
body>
html>