纯css使table表头固定,内容滚动

1. HTML结构

<div class="container">
        <div class="thead">
            <table>
                <thead>
                    <tr>
                        <th>标题1</th>
                        <th>标题2</th>
                        <th>标题3</th>
                        <th>标题4</th>
                        <th>标题5</th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="tbody">
            <table>
                <tbody>
                    <tr>
                        <td>1111</td>
                        <td>2222</td>
                        <td>3333</td>
                        <td>4444</td>
                        <td>5555</td>
                    </tr>
                    <!-- 省略n行tr -->
                    <tr>
                        <td>1111</td>
                        <td>2222</td>
                        <td>3333</td>
                        <td>4444</td>
                        <td>5555</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

2. css样式

       table {
            border: 1px solid #ccc;
            width: 300px;
            text-align: center;
        }
        /* 1. 给tbody的表格固定高度(也可以flex:1), 并添加overflow-y:scroll */
        .tbody {
            height: 150px;
            overflow-y: scroll;
        }
        /* 2. 隐藏滚动条 */
        .tbody::-webkit-scrollbar {
            display: none
        }
        /* 3. 使上下表格对齐(宽度一致) */
        table tr th:nth-of-type(1),
        table tr td:nth-of-type(1) {
            width: 20%;
        }

        table tr th:nth-of-type(2),
        table tr td:nth-of-type(2) {
            width: 20%;
        }

        table tr th:nth-of-type(3),
        table tr td:nth-of-type(3) {
            width: 20%;
        }

        table tr th:nth-of-type(4),
        table tr td:nth-of-type(4) {
            width: 20%;
        }

        table tr th:nth-of-type(5),
        table tr td:nth-of-type(5) {
            width: 20%;
        }

猜你喜欢

转载自blog.csdn.net/xiaomajia029/article/details/80911176