在前端的学习中,使用原生JS的table是很常见的,当内容过多且高度不够时滚动样式是很常见的,故在此记录。
目录
2、给td设置宽度,方便表头与内容对齐,需要注意表头的td和表体的td的宽度要一致,否则会出现错位的情况,这里为了方便都是设置的固定宽度,可根据实际情况使用百分比或者vw
效果
一、HTML
表头和表体拆分,用不同的table包裹
<div class="content">
<!-- 表头 -->
<div class="thead">
<table>
<thead>
<tr>
<th class="w-150">Header 1</th>
<th>Header 2</th>
</tr>
</thead>
</table>
</div>
<!-- 表体 -->
<div class="tbody">
<table>
<tbody>
<tr>
<td class="w-150">Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 2 Data 1</td>
<td>Row 2 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 3 Data 1</td>
<td>Row 3 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 4 Data 1</td>
<td>Row 4 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 5 Data 1</td>
<td>Row 5 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 6 Data 1</td>
<td>Row 6 Data 2</td>
</tr>
</tbody>
</table>
</div>
</div>
二、CSS
1、给最外层容器设置一个固定的宽高,并设置对齐方式
2、给td设置宽度,方便表头与内容对齐,需要注意表头的td和表体的td的宽度要一致,否则会出现错位的情况,这里为了方便都是设置的固定宽度,可根据实际情况使用百分比或者vw
3、标题部分的容器单独设置超过可滚动的样式
.content {
width: 300px;
text-align: left;
}
.thead {
height: 30px;
overflow-y: hidden;
}
.tbody {
height: 100px;
overflow-y: scroll;
}
.w-150 {
width: 150px;
}
.content th,
.content td {
border-bottom: 1px solid #ebeef5;
}
三、完整示例
<template>
<div class="content">
<div class="thead">
<table>
<thead>
<tr>
<th class="w-150">Header 1</th>
<th>Header 2</th>
</tr>
</thead>
</table>
</div>
<div class="tbody">
<table>
<tbody>
<tr>
<td class="w-150">Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 2 Data 1</td>
<td>Row 2 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 3 Data 1</td>
<td>Row 3 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 4 Data 1</td>
<td>Row 4 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 5 Data 1</td>
<td>Row 5 Data 2</td>
</tr>
<tr>
<td class="w-150">Row 6 Data 1</td>
<td>Row 6 Data 2</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
</script>
<style scoped>
.content {
width: 300px;
text-align: left;
}
.thead {
height: 30px;
overflow-y: hidden;
}
.tbody {
height: 100px;
overflow-y: scroll;
}
.w-150 {
width: 150px;
}
.content th,
.content td {
border-bottom: 1px solid #ebeef5;
}
</style>