使用position: sticky;
这种方法适用于大多数现代浏览器,特别是当你想要固定列在滚动时。
html
<style>
.table-container {
overflow-x: auto;
width: 100%;
}
.table-container table {
width: max-content;
border-collapse: collapse;
}
.table-container th, .table-container td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
.table-container th:last-child, .table-container td:last-child {
position: sticky;
right: 0;
background-color: white; /* 确保背景颜色与表格匹配 */
z-index: 100; /* 确保在最上层 */
}
</style>
<div class="table-container">
<table>
<thead>
<tr>
<th>列1</th>
<th>列2</th>
<th>列3</th>
<!-- 更多列 -->
</tr>
</thead>
<tbody>
<tr>
<td>数据1</td>
<td>数据2</td>
<td>数据3</td>
<!-- 更多数据 -->
</tr>
<!-- 更多行 -->
</tbody>
</table>
</div>