最近在做项目是经常用到table表格来做数据统计,数据少时还好,但是数据多就会导致整个页面看起来乱,用户体验不好,为了使得用户体验更好,所以就会为table的内容上显示滚动条,这样即使再多的数据也不怕因为过多导致页面显示难看。
转自: https://www.mybj123.com/667.html
第一种css方法
<table width="80%" border="1">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>单位</th>
</tr>
</thead>
<tbody>
<tr>
<td>刘媛媛</td>
<td>20</td>
<td>百度</td>
</tr>
......
</tbody>
</table>
* {
margin: 0;
padding: 0;
}
table {
/*设置相邻单元格的边框间的距离*/
border-spacing: 0;
/*表格设置合并边框模型*/
border-collapse: collapse;
text-align: center;
}
/*关键设置 tbody出现滚动条*/
table tbody {
display: block;
height: 80px;
overflow-y: scroll;
overflow-x: hidden;
}
table thead,
tbody tr {
display: table;
width: 100%;
table-layout: fixed;
}
/*关键设置:滚动条默认宽度是16px 将thead的宽度减16px*/
table thead {
width: calc( 100% - 1em)
}
table thead th {
background: #ccc;
}
效果如图:
上面的代码虽实现了滚动条功能,但美中不足的是滚动条超出表头thead,留有空隙,体验不好。
第二种方法
固定表头,将表头部分和表体部分分开写
<!-- 表头需要固定的地方 -->
<div id="elec_table">
<div class="table-head">
<table class="table theadstyle">
<thead>
<tr style="background: #ccc;">
<th>IP地址</th>
<th>端口</th>
<th>操作</th>
</tr>
</thead>
</table>
</div>
</div>
<!-- 表体需要显示滚动条的地方 -->
<div class="table-body">
<table class="table table-bordered" id="srvTable">
<tr>
<td>${zkinfo.zkIp }</td>
<td>${zkinfo.zkPort}</td>
</tr>
</table>
</div>
/*外层容器设置高*/
#elec_table{
position:relative;
table-layout : fixed;
}
.table-body{
overflow-y:auto;
overflow-x:hidden;
height:150px;
}
/*设置table-layout:fixed固定宽度,表头和表体需要对齐*/
table{
table-layout:fixed;
}
/*设置单元格的宽度,可能会出现内容长需要换行的情况 使用white-space:normal,每个单元格都是一样的宽度*/
#elec_table td{
width:20%;
white-space:normal;
}
.theadstyle thead tr th{
text-align:center;
}
第三种方法(推荐)
<table>
<thead>
<tr>
<th>Name</th>
<th>Color</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<tr>
<td>Pear</td>
<td>Green</td>
<td>These are green.</td>
</tr>
<tr>
<td>Grape</td>
<td>Purple / Green</td>
<td>These are purple and green.</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
<td>These are orange.</td>
</tr>
<tr>
<td>Banana</td>
<td>Yellow</td>
<td>These are yellow.</td>
</tr>
<tr>
<td>Kiwi</td>
<td>Green</td>
<td>These are green.</td>
</tr>
</tbody>
</table>
table {
width: 100%;
text-align: left;
min-width: 610px;
}
tr {
height: 30px;
padding-top: 10px
}
tbody {
height: 150px;
overflow-y: auto;
overflow-x: hidden;
}
th,td,tr,thead,tbody { display: block; }
td,th { float: left; }
td:nth-child(1),
th:nth-child(1) {
width: 20%;
}
td:nth-child(2),
th:nth-child(2) {
width: 20%;
float: left;
}
td:nth-child(3),
th:nth-child(3) {
width: 59%;
float: left;
}
/* some colors */
thead {
background-color: #333333;
color: #fdfdfd;
}
table tbody tr:nth-child(even) {
background-color: #dddddd;
}
效果如下: