Hello,大家好,我是站长鹏仔,本次鹏仔开发的项目中,实现出功能如图所示,固定表格的头部和左侧,在超出时滚动条滚动悬浮,之前给大家写过一次表格表头固定,是用占位的方式(https://www.sharedbk.com/post/178.html),太麻烦了,本次给大家分享一个更简单的方法。
本次主要用到的css属性是粘性定位 position: sticky; 这个属性可以理解为 position: relative; 正常显示时没有任何变化,但是当页面滚动时,他就相当于 fixed 一样固定到某个位置,一般常用于标题、操作栏、表格表头等。
【PS】 需要配合 top、right、bottom、left 使用才会出现固定效果。
下方鹏仔简单给大家写的案列,可自行复制尝试。
CSS<style>
body,div,p,ul,ol,li,dl,dt,dd,table,tr,td,form,hr,h1,h2,h3,h4,h5,h6,fieldset,img,input {
margin: 0;
padding: 0;
}
body,html {
width: 100%;
min-height: 100%;
}
.table-layer{
width: 600px;
max-height: 200px;
overflow: scroll;
background: rgba(0,0,0,.1);
}
table thead tr{
position: sticky;
top: 0;
z-index: 10;
}
.table-name{
background: #F5F5F5;
position: sticky;
left: 0px;
z-index: 11;
}
.table-name div{
width: 128px;
padding: 12px 8px;
box-sizing: border-box;
text-align: center;
}
.table-con{
min-width: 240px;
padding: 12px 8px;
box-sizing: border-box;
}
</style>
HTML
<div class="table-layer">
<table border="1" cellspacing="0" cellpadding="0">
<thead>
<tr style="background: #F5F5F5; top: 0;z-index: 12;">
<td class="table-name">
<div>姓名</div>
</td>
<td class="table-con">
<div>姓名</div>
</td>
<td class="table-con">
<div>姓名</div>
</td>
<td class="table-con">
<div>姓名</div>
</td>
<td class="table-con">
<div>姓名</div>
</td>
<td class="table-con">
<div>姓名</div>
</td>
</tr>
</thead>
<tr>
<td class="table-name">
<div>姓名</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
</tr>
<tr>
<td class="table-name">
<div>姓名</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
</tr>
<tr>
<td class="table-name">
<div>姓名</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
</tr>
<tr>
<td class="table-name">
<div>姓名</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
</tr>
<tr>
<td class="table-name">
<div>姓名</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
<td class="table-con">
<div>鹏仔</div>
</td>
</tr>
</table>
</div>
标签:box,姓名,表头,width,固定,table From: https://www.cnblogs.com/tp1996/p/18152404