<分区>
标签 html css html-table
<分区>
我想固定表格的标题。表格存在于可滚动的 div 中。请在此处查看我的代码:http://jsfiddle.net/w7Mm8/114/请给我建议解决方案。
谢谢
我的代码:
<div style="position: absolute; height: 200px; overflow: auto; ">
<div style="height: 250px;">
<table border="1">
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 1, cell 2</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
<td>row 1, cell 2</td>
<td>row 1, cell 2</td>
</tr>
</table>
</div>
</div>
最佳答案
您要做的是将表格的内容与表格的标题分开。
你只想要 <th>
要滚动的元素。
您可以使用 <tbody>
在 HTML 中轻松定义此分隔和 <thead>
元素。
现在表头和表体仍然相互连接,它们仍然具有相同的宽度(和相同的滚动属性)。现在让它们不再像表格一样“工作”,您可以设置 display: block
.这条路<thead>
和 <tbody>
是分开的。
table tbody, table thead
{
display: block;
}
现在你可以将滚动设置到表格的主体:
table tbody
{
overflow: auto;
height: 100px;
}
最后,因为 <thead>
不再与正文共享相同的宽度,您应该为表格的标题设置一个静态宽度:
th
{
width: 72px;
}
您还应该为 <td>
设置静态宽度.这解决了未对齐列的问题。
td
{
width: 72px;
}
<tr>
中元素,包括标题行:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
我希望这就是你的意思。
附录
如果您想更好地控制列宽,让它们之间的宽度不同,当然要保持标题和正文列对齐,您可以使用以下示例:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
关于html - 如何使用 CSS 制作带有固定标题的可滚动表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108208/