Trying to "sync" 2 html tables (apply column widths)

I have 2 tables: table1 ("header table", which has only 1 row with table columns) - and table2 ("data table", which has several rows with all the data).

table1 has the widths assigned to most columns. Now I'm trying to apply the column width from table1 to the first row of table2 (table1 has the same width as table2).

My code is:

var tr1 = $("tr",tblHeader).eq(0); // 1st row from header-table
var tr2 = $("tr",tblData).eq(0);   // 1st row from data-table
var td2 = $("td",tr2);             // all cells from data-table

$('td',tr1).each(function(i)       
{
    var td1 = $(this);                // table1 column header-cell
    var width = (td1.css('width'));   // column-width from header-table
    td1.css('width',width+"px");      // apply width to header-table-cell
    td2.eq(i).css('width',wi+"px");   // apply width to data-table-cell
});

Problem:
when installing td-padding in my css, for example: table td{padding:0px;}everything works fine (both tables have the same column widths). but as soon as I change the overlay to something like table td {padding:2px;padding-left:4px;padding-right:4px;}, the data table spins. When checking column widths with firebug, all columns have the same width (table1 + table2), but they still look different. Any ideas what could be wrong?

+3
source share
1 answer

Why not just one table, for example:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Mike</td>
            <td>26</td>
            <td>USA</td>
        </tr>
        <tr>
            <td>Peter</td>
            <td>27</td>
            <td>Great Britain</td>
        </tr>
        <tr>
            <td>Hans</td>
            <td>26</td>
            <td>Germany</td>
        </tr>
    </tbody>
</table>
0
source

Source: https://habr.com/ru/post/1769919/


All Articles