Css 设置固定表格头部,内容可滚动

 
效果图:
实现这个效果主要用到了<colgroup>标签,来保证表格头部和内容的宽度一致。将头部<thead> 和<tbody>,分别放☞到两个div的<table>标签下。并给表格内容所在的div
设置一个固定高度即可。
样式  calc(100% - 1em) 来给滚动条预留1em的宽度。
 
<colgroup>标签的属性定义:
属性
描述
span
数值
规定列组应该横跨的列数
width
像素大小 、占比%
规定列组合的宽度
align
left
right
center
justify
..
规定列组合的垂直对齐方式
 
  • 表格css样式
 
<style>
    .main {
        margin:30px auto;
        width: 1000px;
        height: auto;
        font-size: 13px;
        font-family: serif;
        overflow: hidden;
    }
    table {
        border-spacing: 0;
        border-collapse: collapse
    }
    table th {
        background-color: #F4F5F7;
    }
    table, table td, table th {
        border: 1px solid #d3d7dc;
    }
        table td, table th {
            padding: 7px;
            height: 26px;
            line-height: 26px;
        }
    .thead_table {
        width: calc(100% - 1em);
    }
    .div_tbody {
        height: 600px;
        overflow: auto;
    }
    .table_tbody {
        width: 100%;
    }
    /*设置滚动条*/
    .div_tbody::-webkit-scrollbar {
        width: 1em;
    }
/* 若去掉下面部分css,将保留滚动效果,而滚动条不会显示 */ .div_tbody::-webkit-scrollbar-track { background-color: rgba(217, 210, 210, 0.41); -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius: 2em; } .div_tbody::-webkit-scrollbar-thumb { background-color: rgba(128, 128, 128, 0.43); -webkit-border-radius: 2em; -moz-border-radius: 2em; border-radius: 2em; } </style>

  

  • 表格html代码
 
<div class="main">
    <div>
        <table cellpadding="0" cellspacing="0" class="thead_table">
            <colgroup>
                <col span="5" width="20%" />
            </colgroup>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>爱好</th>
                </tr>
            </thead>
        </table>
    </div>
    <div class="div_tbody">
        <table cellpadding="0" cellspacing="0" class="table_tbody">
            <colgroup>
                <col span="5" width="20%" />
            </colgroup>
            <tbody>
                @for (var i = 0; i < 20; i++)
                {
                <tr>
                    <td>@i</td>
                    <td>第 @i 梦</td>
                    <td>@(i / 2 == 1 ? "女" : "男")</td>
                    <td>@(i / 2 == 0 ? 18 : 19)</td>
                    <td>无</td>
                </tr>
                }
            </tbody>
        </table>
    </div>
</div>

  

 
 
 
 
 
posted @ 2019-11-27 17:50  云水边静沐暖阳丶  阅读(1981)  评论(0编辑  收藏  举报