1

I have two tables and want to sync their column width using Javascript. It works as expected in Google Chrome as long as I don't set the CSS property border-collapse: collapse; for my tables.

When I do this, the sync doesn't work properly in Google Chrome. In Firefox everything is still working as expected, though.

I tried this as suggested at https://stackoverflow.com/a/3580766 but with no success:

$("#t1").width($("#t2").width());
$("#t1 tr td").each(function (i){
       $(this).width($($("#t2 tr:first td")[i]).width());
})

See this JSFiddle for a complete example and an other approach I tried also: http://jsfiddle.net/gnskjveq/3/

What am I missing here? Why is this working like a charm in Firefox and gives so bad results in Google Chrome?

My example tables:

<table id="t1" class="standard"> 
<tr> 
    <td>Name</td><td>User Image</td><td>Email</td><td>Favorite Language</td>
</tr>
</table>

<!-- table "t2" intended to have equal column widths -->
<table id="t2" class="standard">
<tr>
<!-- Lots of crazy stuff of wildly varying widths -->
    <td>12345678901234567890A</td>
    <td>123456789012345678901234567890A</td>
    <td>12345678901234567890A</td>
    <td>1234567890A</td>
</tr>
<tr>
<!-- Lots of crazy stuff of wildly varying widths -->
    <td>12345678901234567890A</td>
    <td>1234567890A</td>
    <td>123456789012345678901234567890A</td>
    <td>12345678901234567890A</td>
</tr>
<tr>
<!-- Lots of crazy stuff of wildly varying widths -->
    <td>12345678901234567890A</td>
    <td>1234567890A</td>
    <td>123456789012345678901234567890A</td>
    <td>12345678901234567890A</td>
</tr>
</table>

And the corresponding CSS (SCSS to be exact):

table.standard {
    border-collapse: collapse;
    td, th {
        border-right: 3px solid black;
        border-bottom: 3px solid black;
        padding: 8px;
        margin: 0px;
    }
}
Community
  • 1
  • 1
Thilo
  • 234
  • 1
  • 8

1 Answers1

1

First, make sure to explicitly specify the table-layout CSS property of your tables to fixed:

table.standard {
    table-layout: fixed;
    [...]
}

Second, after you've adjusted the width of your columns, your tables are not the same size anymore. Make sure they are by executing the following Javascript:

var table_width = $("#t1").width()
$("#t1, #t2").width(table_width);

A complete JSFiddle demo that works in Chrome and Edge is available here.

mbinette
  • 5,094
  • 3
  • 24
  • 32
  • wow, that's exactly what I was looking for. I tried `table-layout: fixed;` before, but I didn't recognize, the table sizes were not the same afterwards. Your JSFiddle works in Firefox, too :) – Thilo Oct 02 '15 at 13:43