Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make multiple html tables have the same column widths

I have multiple html tables. Each table has the same number of columns but with different sets of data in each cell.

 <table><tr>
     <td>Col 1 Table 1</td>
     <td>Col 2 Table 1</td>
     <td>Col 3 Table 1</td>
 </tr></table>

 <table><tr>
     <td>Col 1 Table 2</td>
     <td>Col 2 Table 2</td>
     <td>Col 3 Table 2</td>
 </tr></table>

I wanted to figure out the easiest way to have each comparable column across these tables (so each first column, each second column, etc) be the same width so all of the tables line up perfectly.

For some specific reasons, I can't merge these into a single table so I want to see if there is anyway to have multiple tables.

It seems like the tables (regardless of any CSS that I put in) are getting changed based on the data that's in the cell.

Any suggestions?

like image 382
leora Avatar asked Apr 06 '11 15:04

leora


2 Answers

The simplest way is to use the :nth-child selector:

table td:nth-child(1) { width: 100px; }
table td:nth-child(2) { width: 300px; }
table td:nth-child(3) { width: 225px; }
<table>
  <tr>
    <td>Col 1 Table 1</td>
    <td>Col 2 Table 1</td>
    <td>Col 3 Table 1</td>
  </tr>
</table>

<table>
  <tr>
    <td>Col 1 Table 2</td>
    <td>Col 2 Table 2</td>
    <td>Col 3 Table 2</td>
  </tr>
</table>

Alternatively you could give each td its' own class, but this isn't ideal as you need to manually keep tracks of those classes, which can be a pain in a dynamically amended table:

.column-1 { width: 100px; }
.column-2 { width: 300px; }
.column-3 { width: 225px; }
<table>
  <tr>
    <td class="column-1">Col 1 Table 1</td>
    <td class="column-2">Col 2 Table 1</td>
    <td class="column-3">Col 3 Table 1</td>
  </tr>
</table>

<table>
  <tr>
    <td class="column-1">Col 1 Table 2</td>
    <td class="column-2">Col 2 Table 2</td>
    <td class="column-3">Col 3 Table 2</td>
  </tr>
</table>
like image 119
Rory McCrossan Avatar answered Oct 03 '22 08:10

Rory McCrossan


How do you use the css styling? You should set fixed width to cells in first row of each table.

<table>
  <tr>
    <td style="width:100px"></td>
    <td style="width:120px"></td>
 </tr>
 <tr>
   <td></td>
   <td></td>
 </tr>
</table>

Edit: It's of course better to use css classes, but you can change that once you will see if it works for you.

<table>
  <tr>
    <td class="c1"></td>
    <td class="c2"></td>
 </tr>
 <tr>
   <td></td>
   <td></td>
 </tr>
</table>
<!-- ... -->
<table>
  <tr>
    <td class="c1"></td>
    <td class="c2"></td>
 </tr>
 <tr>
   <td></td>
   <td></td>
 </tr>
</table>

etc..

like image 33
Damb Avatar answered Oct 03 '22 07:10

Damb