在前端的学习中,使用原生JS的table是很常见的,故在此记录
效果
一、HTML
<div class="content">
<div class="table">
<table>
<thead>
<tr>
<th class="w-150">Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<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
.content {
width: 300px;
text-align: left;
}
.table {
height: 100px;
overflow-y: scroll;
}
.w-150 {
width: 150px;
}
.content th,
.content td {
border-bottom: 1px solid #ebeef5;
}
三、完整示例
<template>
<div class="content">
<div class="table">
<table>
<thead>
<tr>
<th class="w-150">Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<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;
}
.table {
height: 100px;
overflow-y: scroll;
}
.w-150 {
width: 150px;
}
.content th,
.content td {
border-bottom: 1px solid #ebeef5;
}
</style>