Alex Rivera | Logout

Table Column width must be same for two tables

Asked 2012-08-30T05:11:31.663
43

There are two tables with width 600px and 5 Columns each. But, width has not been set for each column. Here, I want to make columns width must be same in both the tables. You can use CSS or jQuery. And, I dont want to fix the column width manually.

HTML Example:

<table width="600" border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td>hdng 1</td>
        <td>hdng 2</td>
        <td>hdng 3</td>
        <td>hdng 4</td>
        <td>hdng 5</td>
    </tr>
</table>
<table width="600" border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td>content content content</td>
        <td>con</td>
        <td>content content content</td>
        <td>content content content</td>
        <td>content content content</td>
    </tr>
</table>

Any help would be highly appreciated.

Edit
Report

1 Answer

2

If you know that each table will have exactly 5 columns, applying width: 20% is your best bet:

td {
    width: 20%;
}

But if you can have any number of columns, you can instead write a simple JQuery script to figure out how many columns there are and set the widths accordingly.

Here is a JSFiddle demo. I modified the HTML to add id="first" to the first table, so I could get a concrete reference to it. Then the JavaScript is this:

var num = $("table#first tr:first-child > td").length;
var width = (100 / num) + "%";

$("td").css("width", width);​

Basically it grabs the first row of the #first table and counts the number of columns. Then it finds the corresponding percentage width for that number of columns. Then it applies that width to all <td> elements.

This will work as long as there are no colspan defined on the tds, which would throw off the column count. The columns will be equal since you've defined an explicit width on both tables.

answered 2012-08-30T06:06:02.697

Your Answer