首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

HTML 表格表頭固定、無滾動條的 CSS 實現方案

     編輯:程式設計疑難解答

核心 CSS 技術

.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; /* 避免滾動時穿透表頭 */
}

HTML 結構

<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 確保表頭覆蓋內容
  • tbody 背景色防止滾動時內容透出表頭

兼容性

IE 不支持 sticky,需 JS 方案:監聽 scroll 事件動態設置 thead 的 transform: translateY()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved