Table的思索(二):表头固定而内容滚动的表格

      产品要求表格的表头固定,而内容在超出table的高度后,还能自由滚动,如下所示。
这里写图片描述
      直觉的感受是修改thead与tbody,尝试了以下几种方法,但均告失败。
1. 将tbody设置为块状元素,然后设置表格的高度与溢出;
1. 将thead设置为绝对定位,然后设置表格的高度与溢出;
1. 将表格转换为块状元素,然后把有td都设置为浮动,从而控制高度与溢出;

      原因都是彻底破坏了表格的布局,导致元素的排序、大小都彻底混乱了,完全没有发挥表格的优势,后来经过思考,决定采用拼接法,步骤如下:
1. 创建表格容器
1. 创建表头容器,留出滚动条位置,插入表头;
1. 创建表格内容容器,插入表格内容;

      DOM结构的相关HTML代码如下:

<!-- 表格容器,可用于设置整个的边框及高度 -->
<div class="sti-tbl-container">
    <!-- 表头容器,必须留出17px的滚动条位置 -->
    <div class="sti-tbl-header" style="padding-right:17px;">
        <table class="table table-bordered" style="margin-bottom: 0px;border-bottom-style: none;">
            <tr>
                <th style="width : 10%;">#</th>
                <th  style="width : 20%;">First Name</th>
                <th  style="width : 30%;">Last Name</th>
                <th  style="width : 50%;">Username</th>
            </tr>
        </table>
    </div>
    <!-- 表格内容容器-->
    <div class="sti-tbl-body">
        <table class="table table-bordered">
            <tbody>
                <tr>
                    <th scope="row" style="width : 10%;">1</th>
                    <td style="width : 20%;">Mark</td>
                    <td style="width : 30%;">Otto</td>
                    <td style="width : 50%;">@mdo</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

      表格的CSS代码如下:

/* 表格容器样式,用flex布局可保证table内容能铺满剩余空间 */
.sti-tbl-container {
    height : 100%;
    overflow : hidden;
    display : flex;
    flex-direction: column;
}
/* 设置表格的布局方式,用于宽度对齐 */
.sti-tbl-body>table, .sti-tbl-header>table {
    table-layout: fixed;
}
/* 设置表格内容容器,用于铺满整个剩余空间 */
.sti-tbl-container .sti-tbl-body {
    flex-grow : 1;
    overflow-y : scroll;
}
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值