最近自己做开发时,有个固定表格的行和列的 需求。之前对这些没有深入研究。通过这次顺便写一下笔记,后面还可以复习一下。
需求:固定表头 和最后一列
先上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>固定表格行、列</title>
<style>
.main {
width: calc(100vw - 2rem);
height: calc(100vh - 3rem);
overflow: auto;
}
th, td {
width: 400px;
height: 100px;
border: 1px solid gray;
text-align: center;
}
table {
table-layout: fixed;
width: 200px;
}
thead tr th {
position: sticky;
top: 0;
background: wheat;
}
th:last-child {
position: sticky;
right: 0px;
z-index: 2;
background: green;
}
td:last-child {
position: sticky;
right: 0px;
z-index: 2;
background: #00a0e9;
}
th:last-child {
z-index: 33;
}
</style>
</head>
<body>
<div class="main">
<table cellspacing="0">
<thead>
<tr>
<th>1</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th><th>7</th><th>8</th><th>9</th><th>10</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
以上实现的方法主要使用的是两个属性:
- position:sticky;
- table-layouy:fixed;
1、table-layout属性
table-layout 有两个属性值:
- auto(预设值):表格的总宽度决定每个存储(cell)也就是单元格的最大值
- 每个单元格的最大width = 表格总width / 列数
- fixed:表格的总宽度取决与表格width的定义,以及各栏位(column)的width的定义。
- 表格的总width = 表格的宽度 + 各列的width
为了能够实现表格滚动的效果,需要使用table-layout:fixed 的属性,同时设置 表格的width。
table{
table-layout:fixed;
width:300px;
}
2、position 属性
position 属性在前端开发中,经常会使用它。这次固定表格需要使用到的是position:sticky 的设定。sticky的表现类似relative 和fixed 的结合。
当在目标可视区域中 :像relative ,不会有任何变化
但当滚动超出目标可视区域中:它的表现改为fixed ,会固定在提前设定好的目标位置。
注意点:
position:sticky 应用在table上时,只能作用在<th> <td>标签上,并且一定要定义目标位置 left/right/top/bottom ,才会出现固定效果。
table tr th{
position:sticky;
top:0;
}
table tr td{
position:sticky;
right:0;
}