Question

How can I set up a table so that the last n columns use the available width of a table equally?

In detail: I'm generating a HTML table in the backend (ASP.NET MVC) that has two header columns and a varying number of data columns:

ID Region           Data col 1   Data col 2   ... Data col n
_______________________________________________________
 1 Region name 1    data         data             data
 2 Region 2         data         data             data

...

80 Another region   data         data             data

The table has a width=100%, the first and second column (ID and Region) use fixed widths.

The content of the data columns (esp. the headers) can be strings of different length.

How can I setup the CSS/JS so that the remaining columns are sized equally wide - and use the full remaining width of the table?

My first thought was to simply set style="@(100/NumberOfColumns)%;" on the server. However, as the first two columns are fixed width and I do not know the size of the table on the server side, this approach fails.

Was it helpful?

Solution

Fiddle : http://jsfiddle.net/Dadv2/2/

HTML Code :

<table width="100%">
    <tr>
        <td style="width:100px;" class="fixCol">ID Region</td>
        <td style="width:120px;"  class="fixCol">Data</td>
        <td class="Col">Col1</td>
        <td class="Col">New Column</td>
        <td class="Col">Another Column</td>
    </tr>
</table>

JS Code :

$(document).ready(function(){
var tableWidth = $("table").width();
var colCount = $("table td.Col").size();

// gett fixed td Width
fixCol = 0;
$.each($("table td.fixCol"), function(){
    fixCol += $(this).width();    
});

//set remainging td width
var tdWidth = (tableWidth-fixCol)/colCount;


$("table .Col").css('width',tdWidth);
});

OTHER TIPS

Try it this way:

First Column min width : Xpx;
Second Column min width : Ypx;
Last N Columns width : (100/N) %

HTML: (DEMO)

<table width="100%">
    <tr>
        <td style="min-width:100px;">A</td>
        <td style="min-width:300px;">A</td>
        <td style="width:33%;">L</td>
        <td style="width:33%;">L</td>
        <td style="width:33%;">L</td>
    </tr>
</table>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top