如何使用CSS使用固定标题制作可滚动表 [英] How to make Scrollable Table with fixed headers using CSS

查看:105
本文介绍了如何使用CSS使用固定标题制作可滚动表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将表格的标题固定。表格位于可滚动div中。请在此处查看我的代码: http:// jsfiddle.net/w7Mm8/114/ 请给我解决这个问题。

I want to make header of my table fixed.Table is present inside the scrollable div.Please see my code here:http://jsfiddle.net/w7Mm8/114/ kindly suggest me the solution to this.

感谢

我的代码

<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> 元素。
您可以在HTML中使用< tbody> < thead> 元素。


现在,表的头和主体仍然彼此连接,它们仍将具有相同的宽度(和相同的滚动属性)。现在让他们不再工作表格了,你可以设置 display:block 。这样,thead和tbody是分开的。

What you want to do is seperate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easially define this seperation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width(and same scroll propeties). Now to let them not 'work' as a table anymore you can set the display: block. This way thead and tbody are seperated.

table tbody, table thead
{
    display: block;
}



现在可以设置滚动到表的主体:

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

最后,因为thead与主体不具有相同的宽度现在,您应该为表格的标题设置一个静态宽度:

And last, because the thead doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

您还应为 td> 。这解决了未对齐列的问题。

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}



请注意,元素。每一行都应该在< tr> 元素中,包括标题行:


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

我希望这就是你的意思。

I hope this is what you meant.

jsFiddle

jsFiddle

这篇关于如何使用CSS使用固定标题制作可滚动表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆