Alfred
Alfred

Reputation: 21386

How to set HTML table cell width using JavaScript and jQuery

I have a HTML table like the below;

<table style="width: 100%">
<tr>
<td style="width: 30px">cell</td>
<td class="cell">cell</td>
<td class="cell">cellcell</td>
<td class="cell">cellcellcell</td>
<td class="cell">cellcellcellcell</td>
<td class="cell">cellcellcellcellcell</td>
<td class="cell">cellcellcellcellcellcell</td>
<td style="width: 30px">cell</td>
</tr>
</table>

The table is designed to stretch to screen (or a div having specific width). I want equal width for all cells having class="cell" and this works well when the character length of text in all cells having class="cell" are equal. But, I want to fix the cell width even if the character lengths of contents in class="cell" are different.

Also you can see that the first and last cells have fixed width, in pixels and others cell widths are to be calculated on the basis of percentage .. I want equal width for all cells (except first and last with fixed width in pixels).

I think this can be done using Javascript with the help of jQuery, by calculating the table cell widths on document ready, and then adding some function using on window resize and thereby calculating cell widths. The cell widths will be (tablewidth in px - 60px)/6 I am a beginner and I don't know much.. How can I do this using jQuery and (or) Javascript.

It will be very helpful if someone make me a fiddle..

Upvotes: 0

Views: 12261

Answers (1)

Niklas
Niklas

Reputation: 30002

You could just do that with CSS, by applying each td an equal percentage:

td{
 width:   16%;
}

example: http://jsfiddle.net/niklasvh/wKmxD/

With your updated question, you could do it with javascript by first storing the widths into an array, and then referencing that on window resize, and use the aspect ratio difference to place new widths:

var w = [];
var tw = $('table').width();
$('table td').width(function(i,e){
    w[i]=e;
});

$(window).resize(function(){
    $('table td').width(function(i){
    return ($('table').width()/tw)*w[i];
    });
});

http://jsfiddle.net/niklasvh/543D9/

Upvotes: 3

Related Questions