Table header and body are not getting aligned prop

2019-05-22 15:34发布

I have a table of the following format when i m trying to fix its head using the following css, I m losing the alignment , the table header and body are not getting aligned properly..What can I do to overcome this..

#ex_table
{

table-layout: fixed !important;
}

#ex_table thead tr
{
position: fixed !important;

}

Here is the HTML part

<div class="table_div" style="height:400px;width:98%;overflow:scroll">
<table  id="ex_table">
/*thead and tbody populated dynamically via jquery datatables*/
<tfoot id="ex_footer">
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot> 
</table>
</div>

5条回答
来,给爷笑一个
2楼-- · 2019-05-22 15:49

The answer is not that simple, it needs a lot of work. position: fixed does not work as expected when working with table so you will need another approach

Here is a JSFiddle I put together from a bit of searching the web, http://jsfiddle.net/UWS6N/1/

Also found this on Stackoverflow, it's a question already answered and it involves some jQuery, personally i'm a fan of doing things like this with CSS as it's faster.

Table header to stay fixed at the top when user scrolls it out of view with jQuery

Also, please reserve <th> tags only for the header row, using <thead> as a container for that specific row will help with code readability, placing them in the <tfoot> is a standards violation (a bit harsh this expression I know, but I'm a standards advocate and tend to get a bit edgy when I see bad code, that's probably just me)

查看更多
看我几分像从前
3楼-- · 2019-05-22 16:01

You got to set width to your cells strictly:

th, td { width:30px }

查看更多
神经病院院长
4楼-- · 2019-05-22 16:03

I combined the solution proved by @RomanTheGreat and @Smiter ,and wrote a CSS as given below...Eventhough the alignment isnt pitch prefect.This almost got me there

#ex_table
    {
    table-layout: fixed !important;
    }
    #ex_table thead tr
    {
     width:500px !important;
     position: fixed !important;
    }
    #ex_table tbody tr
    {
     width:500px!important;
    } 
    #ex_table th, td { width:100px; }
查看更多
甜甜的少女心
5楼-- · 2019-05-22 16:04

Fixed-positioning keeps an element in the same spot in the viewport no matter where on the page the user is. So if you use this property on the TRs, they all get stacked up in the top left corner of the viewport (browser window).

查看更多
相关推荐>>
6楼-- · 2019-05-22 16:07

Set your thead row width as table width:

#ex_table thead tr
{
  width:98%;
  position: fixed !important;
}
查看更多
登录 后发表回答