Search code examples
htmlcsscss-tablessmart-table

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 */
}

https://plnkr.co/edit/fcdXKE?p=preview

enter image description here


Solution

  • 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');
    for(i=0;i<tds.length;i++){
        var offset=tds[i].offsetLeft- ths[i].offsetLeft;
        var thToSet = headRow.getElementsByTagName("th")[i];
        thToSet.style.marginLeft = offset + "px";
    }