html+css实现表格固定⾸⾏⾸列
今天接到⼀个任务要⽤html+css实现表格固定⾸⾏⾸列,⽔平垂直可以滚动,不可以⽤javascript
要实现这个功能,表格⽆法实现,需要通过布局来实现
⽗容器div内包裹着4个table(1,2,3,4)
在垂直⽅向,1、2列表头固定,3、4垂直滚动
在⽔平⽅向,1、3⾏表头固定,2、4⽔平滚动
要实现这种效果,可以通过position:sticky;这种定位⽅式相当与fixed+relative,将1固定死在左上⾓,设置2垂直固定在顶部,⽔平可滚动,设置3⽔平固定在左边,⽔平可滚动,4相对定位就好啦
具体实现代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
.contain {
border: 1px solid #cdd;
width: 500px;
height: 300px;
overflow: scroll;
position: relative;
float: left;
top: 100px;
left: 50px;
}
th, td, tr {
border: 1px solid #cdd;
height: 30px;
width: 100px;
text-align: center;
}
.tb1 {
background: gray;
position: fixed;
z-index: 10001;
width: 100px;
}
.tb2 {
background: gray;
position: sticky;
top: 0px;
margin-left: 100px;
width: 500px;
z-index: 1000;
}
.
tb3 {
background: gray;
height: 100%;
float: left;
position: sticky;
z-index: 1000;
width: 100px;
}
.tb4 {
left: 100px;
width: 500px;
position: absolute;
}
</style>
</head>
<body>
<div class="contain">
<table class="tb1" cellspacing="0">
<thead>
<th>姓名
</table>
<table class="tb2" cellspacing="0">
<thead>
<th>Java
<th>Python
<th>Golang
<th>Rust
<th>Ruby
</table>
<table class="tb3" cellspacing="0">
<tbody>
css固定定位<tr>
<th>phermis
<tr>
<th>phermis
<tr>
<th>phermis
<tr>
<th>phermis
<tr>
<th>phermis
<tr>
<th>phermis
<tr>
<th>phermis
<tr>
<th>phermis
<tr>
<th>phermis
</table>
<table class="tb4" cellspacing="0">
<tbody>
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
<tr>
<td>100
<td>100
<td>100
<td>100
<td>100
</table>
</div>
</body>
</html>
View Code
花了⼀下午总算是按着⾃⼰的思路实现了,有需要的朋友可以看下浏览器兼容性不是很好,最新⽕狐⽀持,别的未测试