手动实现table 头部固定,body滚动。

以下就用简单粗暴的方法实现table头部固定,body超出部分实现垂直滚动的例子:

html部分
<!DOCTYPE html> 
<html lang="en"> 
 <head> 
 <meta charset="UTF-8" /> 
 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
 <link rel="stylesheet" href="./table.css" /> 
 <title>Document</title>
 </head> 
 <body> 
    <div class="out-div"> 
        <table 
            <thead> 
                 <tr> 
                    <th>名称</th> 
                    <th>日期</th> 
                    <th>其他</th> 
                  </tr> 
               </thead> 
               <tbody> 
                <tr> 
                    <td>A</td> 
                    <td>2020</td> 
                    <td>colors</td> 
                </tr> 
                 <tr> 
                     <td>B</td> 
                     <td>2020</td> 
                     <td>colors</td> 
                 </tr> 
                 <tr> 
                     <td>C</td> 
                     <td>2020</td> 
                     <td>colors</td> 
                 </tr> 
                 <tr> 
                     <td>D</td> 
                     <td>2020</td> 
                     <td>colors</td> 
                 </tr> 
                 <tr> 
                     <td>E</td> 
                     <td>2020</td> 
                     <td>colors</td> 
                 </tr> 
                 <tr> 
                     <td>F</td> 
                     <td>2020</td> 
                     <td>colors</td> 
                 </tr> 
                 <tr> 
                     <td>G</td> 
                     <td>2020</td> 
                     <td>colors</td> 
                 </tr> 
            </tbody> 
        </table>

 </div> 
 </body> 
</html>
css部分 注释部分是关键代码哦
.out-div {
 width: 1000px;
 height: 300px;
 margin: auto;
 margin-top: 50px;
 outline: 1px solid #888888;
 overflow: hidden;
}

table {
 border-collapse: collapse;
 text-align: center;
 width: 100%;
}

/* thead设置 */~~~~
table thead {
 display: table; /* 重要代码 */
 width: 100%;
}

table thead tr th {
 width: 33.3333%;
 height: 40px;
 line-height: 40px;
 background: lightcyan;
 box-sizing: border-box;
 border-bottom: 1px solid #333333;

}

/* tbody设置 */
table tbody {
 display: block; /* 重要代码 */
 height: 260px;
 width: 100%;
 overflow-y: scroll;
 overflow-x: hidden;
 position: relative;
}

table tbody tr {
 width: 100%;
 display: table; /* 重要代码 */ 
}

table tbody tr td {
 width: 33.3333%;
 line-height: 40px;
 text-align: center;
 box-sizing: border-box;
 border-bottom: solid 1px #444444;
}

/* 隐藏滚动条 */
tbody::-webkit-scrollbar {
 display: none;
}

评论

暂无评论