Adding scrollbar to table dynamically using display:block reduces with of thead


I have some jquery that adds a class to tables if the height of the tables exceeds a certain amount as below:

    $(document).ajaxComplete(function () {
        $('table').each(function () {
            tableId = $(this).attr('id');
            tableHeight = $(this).height();

            if (tableHeight > 580) {
                $('#' + tableId).addClass('tableScrollMaxHeight');

Works perfectly, and this is the contents of that class

table {
    width: 100%;

.table thead {
    border: none;
    width: 100%;

.tableScrollMaxHeight {
    height: 50vh;
    overflow-y: scroll;
    width: 100%;
    display: block;

Again worked perfectly until you have a table that doesnt have enough columns to fill the width, so you then end up with everything inside thead and tbody reducing its width to just enough to wrap around the columns, basically everything beneath thead stays to the left and doesn’t extend the full width of the table.

I have to use display: block to use the scroll y, so is there a way I can ensure the thead uses width: 100%

This is how my table looks in part:

<table class="table table-striped table-bordered table-hover tableScrollMaxHeight">
<th><p class="text title textSizeStandard alignCenter text" id="lblModuleIcon">Icon</p></th>

<th><p class="text title textSizeStandard alignCenter text" id="lblModuleName">Name</p></th>
<tr class="hyperlink-row text" data-href="/en/ModuleManagement/Module/80">
<td class="alignCenter">


You can’t use display:block on any table elements and still have them display as a table. It is impossible unless you don’t mind the content not matching up or you force individual widths on all cells.

Not really sure why you would want to scroll the whole table anyway? Usually you scroll the body content and keep the head of the table fixed. These days you can use position:sticky for that very nicely as shown in this codepen.

You could do similar and add the sticky class with js when you don’t want a tall table.