user3249448 user3249448 - 7 months ago 38
HTML Question

HTML CSS , table TH and TD are not in same line

Open below link seems that TH and TD are not in same line. The reason might be because of the scroll bar. How to resolve this issue so that even with scroll TD and TH will in same line?

table {
box-sizing: border-box;
-moz-box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: stretch;
height: 500px; /* this can vary */

enter image description here


Getting the offset of the th, comparing it to the offset of the td, and then setting the margin-left property of the th as the difference of those two should work.

Tested Demo:

// set id on table
var dataTable = document.getElementById("dataTable");
var tableHead = dataTable.getElementsByTagName("thead")[0];
var headRow = tableHead.getElementsByTagName("tr")[0];
var tds = document.querySelectorAll('#dataTable tbody td');
var ths = document.querySelectorAll('#dataTable thead th');
    var offset=tds[i].offsetLeft- ths[i].offsetLeft;
    var thToSet = headRow.getElementsByTagName("th")[i]; = offset + "px";