Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use remaining space equally for n-columns

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.

like image 465
Peter Albert Avatar asked May 13 '14 06:05

Peter Albert


2 Answers

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);
});
like image 165
Arul Avatar answered Oct 08 '22 17:10

Arul


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>
like image 39
loxxy Avatar answered Oct 08 '22 17:10

loxxy