Make all cells in the table the same width equal to the width of the cell

Is it possible to have the same width for all cells in a table that is equal to the width of the widest cell without using a fixed width.

+4
source share
1 answer

Yes it is.

<table> <tr> <td>short</td> <td>longer</td> <td>the longest cell</td> </tr> </table> 
 var max = 0, $cells = $('td'); $cells.each(function () { var width = $(this).width(); max = max < width ? width : max; }); $cells.each(function () { $(this).width(max); }); 

https://jsfiddle.net/uqvuwopd/1/

[EDIT]

As noted in the comments of @connexo in the comments, to handle the case when the table is larger than its maximum size, you need one more logic:

 var max = 0, $cells = $('td'); $cells.each(function () { var width = $(this).width(); max = max < width ? width : max; }); $table = $cells.closest('table'); if ($table.width() < max * $cells.length) { max = 100 / $cells.length + '%'; } $cells.each(function () { $(this).width(max); }); 

https://jsfiddle.net/uqvuwopd/3/

[EDIT]

And this is an ECMA5 based version that does not require jQuery:

 var max = 0, cells = document.querySelectorAll('td'); Array.prototype.forEach.call(cells, function(cell){ var width = cell.offsetWidth; max = max < width ? width : max; }); var table = document.querySelector('table'), uom = 'px'; if (table.offsetWidth < max * cells.length) { max = 100 / cells.length; uom = '%'; } Array.prototype.forEach.call(cells, function(cell){ cell.setAttribute('style','width:' + max + uom); }); 

https://jsfiddle.net/uqvuwopd/4/

+6
source

All Articles