table頭部、尾部固定;中間內容定高自適應滾動
很多時候,需要使用到表格做數據分析,不管是前端展現,還是后台管理系統節點展現
工作過程中遇到了,作為一個小筆記,備忘!
如下圖所示
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------
表格的頭部,和尾部是固定不動的,中間內容隨着內容的增多,而出現滾動條。
<!--container-->
<div class="container">
<table class="form-table" cellpadding="0" cellspacing="0">
<thead class="fixed-thead" id="head">
<tr>
<th>序號</th>
<th>姓名</th>
<th>性別</th>
<th>年齡</th>
</tr>
</thead>
<tbody class="scroll-tbody" id="body">
<tr>
<td>1</td>
<td>張三</td>
<td>男</td>
<td>18</td>
</tr>
</tbody>
<tfoot class="fixed-tfoot">
<tr>
<td>序號</td>
<td>姓名</td>
<td>性別</td>
<td>年1齡</td>
</tr>
</tfoot>
</table>
</div>
<!--container-->
如上html結構簡單。精簡。
/*各個部分樣式*/
@charset "utf-8";
body{
overflow: hidden;
}
.container {
border: 1px #ccc solid;
width: 90%;
margin: 100px auto;
}
.form-table {
width: 100%;
border-collapse: collapse;
margin: 0 auto;
text-align: center;
table-layout: fixed;
}
.form-table th {
border-left: none;
border-top: none;
border-right: 1px #ccc solid;
border-bottom: 1px #ccc solid;
background: #F3F3F3;
}
.form-table td {
border-left: none;
border-top: none;
border-bottom: 1px #ccc solid;
border-right: 1px #ccc solid;
}
.fixed-thead,
.fixed-tfoot {
display: block;
/*width: 99%;*/
width: -webkit-calc(100% - 17px);
width: -moz-calc()(100% - 17px);
width: calc(100% - 17px);
height: 50px;
}
.fixed-tfoot tr td {
background: #F3F3F3;
border-bottom: none;
}
.fixed-thead tr,
.fixed-tfoot tr {
width: 100%;
height: 50px;
line-height: 50px;
display: block;
}
.fixed-thead tr th,
.fixed-tfoot tr td {
float: left;
display: block;
width: 25%;
height: 50px;
font-size: 16px;
text-align: center;
}
.scroll-tbody {
display: block;
height: 306px;
overflow: auto;
width: 100%;
}
.scroll-tbody tr {
width: 100%;
display: block;
height: 40px;
line-height: 40px;
}
.scroll-tbody tr td {
float: left;
display: block;
width: 25%;
}
.form-table .scroll-tbody tr:nth-child(odd) td {
background-color: #ECE9D8;
}
-------------------核心對齊樣式---------------------
width: -webkit-calc(100% - 17px);
width: -moz-calc()(100% - 17px);
width: calc(100% - 17px);
兼容高級瀏覽器
-----------------------------------------------------
為了兼容IE6,可以使用如下 js去實現
<script type="text/javascript">
window.onload=window.onresize=function (){
var body=document.getElementById("body");
var head=document.getElementById("head");
head.style.width=(body.scrollWidth)+"px";
}
</script>
----------------------------------------------------