How to keep the column width in an HTML table equal for all columns based on the widest column

StackOverflow https://stackoverflow.com/questions/13514608

  •  01-12-2021
  •  | 
  •  

Question

I see a lot of questions regarding column width, but I was not able to find an answer for a scenario exactly like mine.

Here is my table:

<table>
    <tr>
        <td colspan="3">Title goes here</td>
        <td>A</td>
        <td class="right">B</td>
    </tr>

    <tr>
        <td rowspan="3">C</td>
        <td>D</td>
        <td>E</td>
        <td>F</td>
        <td class="right">G</td>
    </tr>

    <tr>
        <td>H</td>
        <td colspan="2" class="center">I</td>
        <td rowspan="2" class="right">J</td>
    </tr>

    <tr>
        <td>K</td>
        <td>L</td>
        <td>M</td>
    </tr>

    <tr>
        <td class="right">N</td>
        <td colspan="4" class="center">O</td>
    </tr>
</table>

and here is my CSS:

<style>
    table 
    {
        table-layout: fixed;

    }

    table, td 
    {
        border: 1px solid;
    }

    .right 
    {
        text-align:right;
        vertical-align:bottom;
    }
    .center 
    {
        text-align: center;
    }
</style>

What I want to achieve is all five columns to have the same width based on the widest one. The idea is that I don't know how big the title will be. I know that I could set a fixed width for the table (e.g. 200px or 100%), but I don't want to do that. I want both the width of the columns and the width of the table to expand as the title expands. And as you can see the title spans three columns.

Était-ce utile?

La solution

I’m afraid this cannot be done in HTML, even with the help of CSS. You need some scripting too: a script that processes the table after the browser has formatted it, finds out the widest column, and sets all columns to that width. Assuming your table element has id=t, the following pure JavaScript code does the job:

<script>
window.onload = function () {
var tbl = document.getElementById("t");
var row = tbl.rows[0];
var maxWidth = 1;
for ( var i = 0; i < row.childNodes.length; i++ ) {
  var width = row.childNodes[i].offsetWidth;
  if(width > maxWidth) { maxWidth = width; } 
  }
for ( var i = 0; i < row.childNodes.length; i++ ) {
  row.childNodes[i].style.width = maxWidth + "px"; 
  }
}
</script>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top