【发布时间】:2012-09-26 08:48:27
【问题描述】:
有没有人知道一种仅使用 html 和 css 使表格主体可滚动的普通方法?
显而易见的解决方案
tbody {
height: 200px;
overflow-y: scroll;
}
不工作。
这不是表格的明显用途吗?
我做错了吗?
【问题讨论】:
标签: html css css-tables
有没有人知道一种仅使用 html 和 css 使表格主体可滚动的普通方法?
显而易见的解决方案
tbody {
height: 200px;
overflow-y: scroll;
}
不工作。
这不是表格的明显用途吗?
我做错了吗?
【问题讨论】:
标签: html css css-tables
你需要先声明一个高度,否则你的表格会根据它的内容展开。
table{
overflow-y:scroll;
height:100px;
display:block;
}
编辑:澄清你的问题后,我编辑了小提琴: 查看this Example 或that way。它相当hacky并且不能保证跨浏览器工作,但可能适用于您的情况。
【讨论】:
thead 部分会发生什么情况?
display:block 会起作用,但通常不推荐使用,因为浏览器将不再将其视为表格。
你不能用桌子做到这一点。用 div 包裹表格,给它类似:
div.wrapper {
overflow:hidden;
overflow-y: scroll;
height: 100px; // change this to desired height
}
【讨论】:
您可以用父 div 包裹表格,并按照 scoota269 的建议让他可滚动:
.div_before_table {
overflow:hidden;
overflow-y: scroll;
height: 500px;
}
为了保持表格标题的粘性,您可以添加fixed 类:
.th.fixed {
top: 0;
z-index: 2;
position: sticky;
background-color: white;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #ddd;
}
/* The scrollable part */
.scrollable {
height: 150px;
overflow-y: scroll;
border-bottom: 1px solid #ddd;
}
th {
position: sticky;
background-color: white;
z-index: 2;
top: 0;
}
<div class="scrollable">
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
</div>
【讨论】:
你想要这样的东西吗?
带有固定标题的纯 CSS 可滚动表格(一)
http://anaturb.net/csstips/sheader.htm
http://www.scientificpsychic.com/blogentries/html-and-css-scrolling-table-with-fixed-heading.html
【讨论】: