Table header and body are not getting aligned prop

2019-05-22 15:53发布

问题:

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>

回答1:

You got to set width to your cells strictly:

th, td { width:30px }



回答2:

Set your thead row width as table width:

#ex_table thead tr
{
  width:98%;
  position: fixed !important;
}


回答3:

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)



回答4:

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).



回答5:

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; }