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>

  

 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM