Is it possible to have the same width on all cells in a table that is equal to the widest cell's width without using fixed widths.
Asked
Active
Viewed 1,982 times
4
-
Here's an answer I recently posted on table cell width behavior. Hope it helps. [Managing the Width of HTML Table Cells
](http://stackoverflow.com/a/31822882/3597276) – Michael Benjamin Aug 11 '15 at 23:52
1 Answers
6
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 @connexo pointed out in the comments some more logic is needed to handle the case when the table would be larger than its maximum size:
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 a version based on ECMA5 that doesn't 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);
});

Andrea Casaccia
- 4,802
- 4
- 29
- 54
-
This works only as long as there is enough space available. https://jsfiddle.net/uqvuwopd/2/ If not, the cells with less content will ignore the `width` you applied. – connexo Aug 11 '15 at 15:37
-
-
I meant that of course it works only as long as there is enough space available... The OP didn't require any special behaviour in that case :) – Andrea Casaccia Aug 11 '15 at 15:46
-
1There was no necessity to "require special behaviour in that case" since they clearly stated they want a solution that creates equal width columns. The fact that they didn't talk about available horizontal resolution invalidates the requirement only in your interpretation. – connexo Aug 11 '15 at 15:53
-
`var max = 0, $cells = $('td'), $table = $cells.closest('table'); $cells.each(function () { var width = $(this).width(); max = max < width ? width : max; }); $table[0].width($cells.length*max); $cells.each(function () { $(this).width(33.333333%); });` – connexo Aug 11 '15 at 15:55
-
Is it possible to set at once also the min-width value of each cell? – Patryk Imosa Aug 12 '15 at 07:09