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

本文介绍了一种使用HTML和CSS实现的滚动表格布局方案,通过设置tbody的高度和滚动条隐藏等属性,解决了长表格超出显示区域的问题,同时确保了表头与内容对齐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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%;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值