In the following example, the offsetTop
of tr
rows in a table returns different results for Firefox and Chrome(Brave version) when a td
within the tr
has a border top and bottom.
I was expecting the first tr
to have an offsetTop
of 0
but in Firefox it is 1
because of the border width. At least when there are no borders the offsetTop
is 0
.
Having easy access to the offsetTop of all tr in a table regardless of the number of tbody elements they may be contained within, and the fact that the tr.rowIndex
is automatically updated as rows are added/deleted/re-ordered makes table
very useful.
Is this simply a browser difference (or error in Firefox) and is there a way to adjust the CSS to get a 0
or get a 1
in Chrome?
Perhaps I’m overlooking the obvious, but thank you for any guidance you may be able to provide.
let
tr = document.querySelectorAll('tr')
l = tr.length
;
for (let i = 0; i < l; i++ )
console.log(`${tr[i].offsetTop} ${tr[i].offsetHeight}`);
* {
box-sizing: border-box;
}
table {
border-collapse: collapse;
}
table, tbody, tr {
border: 0;
margin: 0;
padding: 0;
}
td {
border-color: transparent transparent rgb(221,232,237) transparent;
border-style: solid;
border-width: 0.1rem 0 0.1rem 0;
}
<table>
<colgroup>
<col class="track">
</colgroup>
<tbody>
<tr><td>Row index 0</td></tr>
<tr><td>Row index 1</td></tr>
<tr><td>Row index 2</td></tr>
</tbody>
</table>
Firefox
1 25
26 25
51 25
Chrome (Brave)
0 25
25 25
50 25
The results are the same if move the border to the tr
only.
let
tr = document.querySelectorAll('tr')
l = tr.length
;
for (let i = 0; i < l; i++ )
console.log(`${tr[i].offsetTop} ${tr[i].offsetHeight}`);
* {
box-sizing: border-box;
}
table {
border-collapse: collapse;
}
table, tbody, tr {
border: 0;
margin: 0;
padding: 0;
}
tr {
border-color: transparent transparent rgb(221,232,237) transparent;
border-width: 0.1rem 0 0.1rem 0;
border-style: solid;
}
<table>
<colgroup>
<col class="track">
</colgroup>
<tbody>
<tr><td>Row index 0</td></tr>
<tr><td>Row index 1</td></tr>
<tr><td>Row index 2</td></tr>
</tbody>
</table>