Patryk Imosa
Patryk Imosa

Reputation: 814

Make all cells in a table have the same width equal to widest cell width

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.

Upvotes: 4

Views: 2090

Answers (1)

Andrea Casaccia
Andrea Casaccia

Reputation: 4971

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);
});

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

Upvotes: 6

Related Questions