.table-container {
max-height: 400px;
overflow-y: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
thead th {
position: sticky;
top: 0;
background: #f5f5f5;
z-index: 1;
border-bottom: 2px solid #ddd;
}
tbody td {
background: white; /* 避免滾動時穿透表頭 */
}
<div class="table-container">
<table>
<thead>
<tr><th>列1</th><th>列2</th></tr>
</thead>
<tbody>
<tr><td>數據</td><td>數據</td></tr>
<!-- 更多行 -->
</tbody>
</table>
</div>
position: sticky; top: 0:現代瀏覽器原生支持表頭固定overflow-y: auto 提供滾動上下文z-index: 1 確保表頭覆蓋內容IE 不支持 sticky,需 JS 方案:監聽 scroll 事件動態設置 thead 的 transform: translateY()。