datatable jquery - table header width not aligned with body width

CAUSE

Most likely your table is hidden initially which prevents jQuery DataTables from calculating column widths.

SOLUTION

  • If table is in the collapsible element, you need to adjust headers when collapsible element becomes visible.

    For example, for Bootstrap Collapse plugin:

    $('#myCollapsible').on('shown.bs.collapse', function () {
       $($.fn.dataTable.tables(true)).DataTable()
          .columns.adjust();
    });
    
  • If table is in the tab, you need to adjust headers when tab becomes visible.

    For example, for Bootstrap Tab plugin:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
       $($.fn.dataTable.tables(true)).DataTable()
          .columns.adjust();
    });
    

Code above adjusts column widths for all tables on the page. See columns().adjust() API methods for more information.

RESPONSIVE, SCROLLER OR FIXEDCOLUMNS EXTENSIONS

If you're using Responsive, Scroller or FixedColumns extensions, you need to use additional API methods to solve this problem.

  • If you're using Responsive extension, you need to call responsive.recalc() API method in addition to columns().adjust() API method. See Responsive extension – Incorrect breakpoints example.

  • If you're using Scroller extension, you need to call scroller.measure() API method instead of columns().adjust() API method. See Scroller extension – Incorrect column widths or missing data example.

  • If you're using FixedColumns extension, you need to call fixedColumns().relayout() API method in addition to columns().adjust() API method. See FixedColumns extension – Incorrect column widths example.

LINKS

See jQuery DataTables – Column width issues with Bootstrap tabs for solutions to the most common problems with columns in jQuery DataTables when table is initially hidden.


I solved this problem by wrapping the "dataTable" Table with a div with overflow:auto:

.dataTables_scroll
{
    overflow:auto;
}

and adding this JS after your dataTable initialization:

jQuery('.dataTable').wrap('<div class="dataTables_scroll" />');

Don't use sScrollX or sScrollY, remove them and add a div wrapper yourself which does the same thing.