Xav*_*avi 62 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>Run Code Online (Sandbox Code Playgroud)
nkm*_*mol 56
您要做的是将表的内容与表的标题分开.您只想<th>滚动元素.您可以使用<tbody>和<thead>元素轻松地在HTML中定义此分隔.
现在表格的标题和正文仍然相互连接,它们仍然具有相同的宽度(和相同的滚动属性).现在让他们不再"工作"作为一个表,你可以设置display: block.这种方式<thead>和<tbody>分开.
table tbody, table thead
{
display: block;
}
Run Code Online (Sandbox Code Playgroud)
现在您可以将滚动设置为表格的主体:
table tbody
{
overflow: auto;
height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
最后,因为<thead>它不再与正文共享相同的宽度,所以应该为表格的标题设置一个静态宽度:
th
{
width: 72px;
}
Run Code Online (Sandbox Code Playgroud)
您还应该为其设置静态宽度<td>.这解决了未对齐列的问题.
td
{
width: 72px;
}
Run Code Online (Sandbox Code Playgroud)
<tr>元素中,包括标题行:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
Run Code Online (Sandbox Code Playgroud)
我希望这就是你的意思.
附录
如果您希望更多地控制列宽,让它们之间的宽度不同,并且当然保持标题和主体列对齐,您可以使用以下示例:
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; }
Run Code Online (Sandbox Code Playgroud)
我可以想到一种厚颜无耻的方法来做到这一点,我认为这不是最好的选择,但它会起作用。
将标题创建为单独的表格,然后将另一个放在 div 中并设置最大大小,然后使用 允许滚动进入overflow。
table {
width: 500px;
}
.scroll {
max-height: 60px;
overflow: auto;
}Run Code Online (Sandbox Code Playgroud)
<table border="1">
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
</table>
<div class="scroll">
<table>
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>
</table>
</div>Run Code Online (Sandbox Code Playgroud)