核心思想:
- 首先是给
tbody
设置display:block;
把行内变成块元素,然后给tbody
一个固定高度 和 overflow-y:scroll;,确保tbody多余的内容可以滑动。 - 给
thead
和tbody tr
设置display:table;
,主要是table-layout:fixed;
,每个单元格均匀分配 - 为了
thead
和tbody
对齐,给thead
宽度 减去滚动条默认宽度(window.innerWidth - document.body.clientWidth = 17px
),这样就能对齐了。还可以给thead
一个背景颜色,突出显示,下面是完整代码,复制粘贴即可使用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.table tbody {
display: block;
height:200px;
overflow-y:scroll;
}
.table thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;
box-sizing: border-box;
}
.table thead {
width: calc( 100% - 17px );
background-color: #ddd;
}
</style>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<body>
<table border="1" cellpadding="1" cellspacing="0" class="table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
</tbody>
</table>
</body>
<script>
</script>
</html>
网友评论