tags:

views:

361

answers:

4

I have 2 HTML tables that are directly on top of each other. Each table has the same number of columns, but the text they contain can differ. And each table can contain many rows. I would like for these 2 tables to have the exact same column width so that the columns always line up. I don't mind if the text within the columns wraps as much as necessary. And I cannot combine all the rows into a single table for other reasons.

Is there some way to make this happen?

Note that this solution only has to work in Firefox and the last 2 versions of IE.

A: 

Just specify the appropriate width in the first row of each column in the table:

style="width:300px";
Kevin
Whilst this works, it doesn't lead to a fluid layout where the table occupies as much space as needed.
belugabob
Correct, but I don't know if in this scenario that is possible.
Kevin
It looks like this won't work if one of the tables has a long word that cannot fit within the specified column width. The browser will wrap the text on spaces, but won't break up a single word. Any idea how to get around that?
Shane
@shane, I'll have to think about that for a moment.
Kevin
+1  A: 

As far as I know you can't align the columns of two tables.

You can create one table and use the css to make it look like two.

<table>
  <tr> <!-- First table header --> </tr>
  <tr> <!-- First table rows... --></tr>
  <tr> <!-- First table footer... --></tr>
  <tr> <!-- Empty space between tables --> </tr>
  <tr> <!-- Second table header --> </tr>
  <tr> <!-- Second table rows... --></tr>
  <tr> <!-- Second table footer... --></tr>
</table>
Gamecat
I've done this before with CSS making the borders as needed. It feels like a cheat, but it did work for me.
Tracy Probst
A: 

I suggest using percentage widths on your columns, making sure that those widths always add up to 100%.

<style type="text/css">
  table { width: 100%; }
  td.colA { width: 30%; }
  td.colB { width: 70%; }
</style>

<table>
  <tr>
   <td class="colA">Lorem ipsum</td>
   <td class="colB">Lorem ipsum</td
  </tr>
</table>

<table>
  <tr>
   <td class="colA">Lorem ipsum</td>
   <td class="colB">Lorem ipsum</td
  </tr>
</table>
skybondsor
A: 

Table cells are fluid by nature, so that is not possible in just html / css unless you give the columns a fixed width (fixed can of course also be a percentage).

You could of course use javascript to find the widest table, get its column widths and use those values for the smaller table, but the solution suggested by belugabob as a comment to your question is far better.

jeroen