111

I am using jQuery datatables. When running the application, the header width is not aligned with the body width. But when I click on the header, it is getting aligned with the body width but even then there is some light misalignment. This problem occurs only in IE.

JSFiddle

This is how it looks when the page gets loaded:

enter image description here

After clicking on the header:

enter image description here

My datatable code:

$("#rates").dataTable({
    "bPaginate": false,
    "sScrollY": "250px",
    "bAutoWidth": false,
    "bScrollCollapse": true,
    "bLengthChange": false,
    "bFilter": false,
    "sDom": '<"top">rt<"bottom"flp><"clear">',
    "aoColumns": [{
            "bSortable": false
        },
        null,
        null,
        null,
        null
    ]
});

rates is my table id.
Could anyone help me with this?

9
  • Could you create a jsFiddle so we can see and test the issue? jsfiddle.net
    – cfs
    Jun 21, 2013 at 14:37
  • I cant create a jsfiddle. There are some DB dependencied in my code.
    – kishore
    Jun 21, 2013 at 14:40
  • could you mock up the table with local data? using the aaData param?
    – cfs
    Jun 21, 2013 at 14:41
  • That is why I have attached the screenshot so that you can guess where it is going wrong.
    – kishore
    Jun 21, 2013 at 14:42
  • cfs : Can you guess from the screenshot? I have also added the datatable code
    – kishore
    Jun 21, 2013 at 14:43

39 Answers 39

107

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.

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.

0
72

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.

4
  • you need to add also position:relative otherwise labels in header will stay fixed without following the scrolling of the wrapper.
    – alexroat
    Jan 2, 2014 at 10:43
  • 4
    I have tried 10+ solution advices but none of them help me except this. Thanks! Feb 15, 2019 at 12:35
  • I just disable the sScrollX, sScrollY, then it works
    – Larry Cai
    Apr 17, 2019 at 9:15
  • 1
    @LarryCai saved the day. Tried so many things and suggestion and all I had to do was comment out scrolly. Thanks.
    – NoBullMan
    Oct 17, 2020 at 16:01
26

Found the solution :

Added table-layout:fixed to the table. And opened the application in IE mode.

4
  • Do you mean add option or add a name for class attr? Aug 8, 2014 at 7:57
  • 10
    @JaxSwagger - Just put up a message saying, "This page uses a broken plugin that only works in IE" lmao
    – Christine
    Jul 14, 2016 at 21:19
  • You made my day, thanks a lot ! And @Shaggy , just add a browser detection ;)
    – Ritooon
    Aug 19, 2019 at 15:45
  • worked for me in 2022 Jul 20, 2022 at 8:29
18

Use these commands

$('#rates').DataTable({
        "scrollX": true,
        "sScrollXInner": "100%",
    });
1
  • Thanks! Didn't know sScrollXInner existed.
    – Crazybud
    Aug 12, 2021 at 18:54
15

I fixed, Work for me.

var table = $('#example').DataTable();
$('#container').css( 'display', 'block' );
table.columns.adjust().draw();

Or

var table = $('#example').DataTable();
table.columns.adjust().draw();

Reference: https://datatables.net/reference/api/columns.adjust()

1
  • 1
    What type of element is "container"? Jul 17, 2019 at 16:10
9

When scrolling is enabled in DataTables using scrollX or scrollY parameters, it will split the entire table into two or three individual HTML table elements; the header, the body and, optionally, the footer. This is done in order to provide the ability to scroll the different sections of the DataTable in a cross-browser manner.

In my case I wanted to have horizontal scroll bar because content are scrolling to right. So adding "scrollX" parameter created this issue in some of the pages which are having more columns.

Below code wrap a div around the DataTable with style "overflow as auto". We need to add div when dataTable completed the execution. We can do this as below:

$('#DataTableID').DataTable({
  //"scrollX": true,            
  "initComplete": function (settings, json) {  
    $("#DataTableID").wrap("<div style='overflow:auto; width:100%;position:relative;'></div>");            
  },
});

If you are using the scrollX,scrollY, scrollXInner or sScrollXInner options - remove them. They may cause problems.

Source: http://sforsuresh.in/datatables-header-body-not-aligned

3
  • This trick fixed my issue. Many thanks!.
    – ASammour
    Nov 8, 2021 at 17:06
  • great solution, better than the broken "scrollX" prop
    – L4marr
    May 9, 2022 at 12:58
  • Best answer ever, I've tried all the answers on this page, but nothing works, except this.
    – Rigsto
    Jun 18 at 15:33
6

As Gyrocode.com said "Most likely your table is hidden initially which prevents jQuery DataTables from calculating column widths."

I had this problem too and solved it by just init the dataTable after showing the div

For example

$('#my_div').show();
$('#my_table').DataTable();
6

issue is data table is called before the data table is drawn on DOM,use set time out before calling data table.

setTimeout(function(){ 
    var table = $('#exampleSummary').removeAttr('width').DataTable( {
        scrollY:        "300px",
        scrollX:        true,
        scrollCollapse: true,
        paging:         true,
        columnDefs: [
            { width: 200, targets: 0 }
        ],
        fixedColumns: false
    } );
}, 100);
6

do not need to come up with various crutches, table header width not aligned with body, because due to the fact that the table did not have enough time to fill in the data for this, do setTimeout

   setTimeout(function() {
     //your datatable code 
  }, 1000);
1
  • Thanks you saved me!
    – Ganesh
    Nov 24, 2020 at 19:58
6

This code will align the header with the body. data-table-basic is the id of the data table I gave.

<style>    
    #data-table-basic_wrapper .dataTable, #data-table-basic_wrapper .dataTables_scrollHeadInner {
        width: 100% !important;
    }
</style>
4

None of the above solutions worked for me but I eventually found a solution that did.

My version of this issue was caused by a third-party CSS file that set the 'box-sizing' to a different value. I was able to fix the issue without effecting other elements with the code below:

    $table.closest(".dataTables_wrapper").find("*").css("box-sizing","content-box").css("-moz-box-sizing","content-box");

Hope this helps someone!

1
  • Yet I have problems with iceweasel (firefox debianized)... works perfectly with chrome
    – tonjo
    Apr 16, 2015 at 18:51
4

make sure table width is 100%

Then "autoWidth":true

3
  • 3
    It is beneficial to provide the exact code with your answer. For javascript/css answers, a JSFiddle is appreciated.
    – Suever
    Feb 1, 2016 at 15:11
  • Table width: 100% does nothing when autoWidth is true, which sets width in pixels inline, effectively overriding the 100% rule. autoWidth will fix the issue alone, but you can not have 100% width tables then, which at least for me is deal breaker.
    – ruuter
    Mar 25, 2019 at 10:42
  • interestingly, width 100% solved my issue alone, thanks for pointing to the right direction !!
    – Irf
    Feb 16, 2020 at 7:25
4

After a ton of hours, I just removed scrollY from options and it's working fine

1
  • Mine was breaking after collapsing the side menu bar, but I found calling draw() corrects it.
    – BVernon
    Mar 6 at 19:51
3
$("#rates").dataTable({
"bPaginate": false,
"sScrollY": "250px",
"bAutoWidth": false,
"bScrollCollapse": true,
"bLengthChange": false,
"bFilter": false,
"sDom": '<"top">rt<"bottom"flp><"clear">',
"aoColumns": [{
        "bSortable": false
    },
    null,
    null,
    null,
    null
]}).fnAdjustColumnSizing( false );

Try calling the fnAdjustColumSizing(false) to the end of your datatables call. modified code above.

Discussion on Column sizing issue

2
  • 1
    If that doesn't fix it do you by chance have some surrounding CSS causing the issue. Can you disable your CSS and see if the scrolling and column widths function as expected. Jun 21, 2013 at 15:03
  • 1
    @MikeRamsey.thanks for the clue fnAdjustColumnSizing( false );
    – scott
    Oct 3, 2018 at 16:23
3

from this answer

var table = $('#example').DataTable();
table.columns.adjust().draw();

to

setTimeout(function () {
        var table = $('#example').DataTable();
        table.columns.adjust().draw();
    }, 3000);

to work!!!!

2
  • the only solution which solve the issue was this answer Aug 16, 2022 at 20:08
  • It worked after adding this
    – Jay
    May 22 at 22:50
2

None of the above solutions worked for me, so I'll post my solution: I was loading the table into a hidden div and then showing the div after the table was built. When I showed/unhid the div first and then built the table while the table was visible, it worked.

So DataTables can't size columns in a hidden div, likely because it is getting a column width of 0px on the backend when the table is hidden.

1

Simply wrap table tag element in a div with overflow auto and position relative. It will work in chrome and IE8. I've added height 400px in order to keep table size fixed even after reloading data.

table = $('<table cellpadding="0" cellspacing="0" border="0" class="display" id="datat"></table>').appendTo('#candidati').dataTable({
        //"sScrollY": "400px",//NO MORE REQUIRED - SEE wrap BELOW
        //"sScrollX": "100%",//NO MORE REQUIRED - SEE wrap BELOW
        //"bScrollCollapse": true,//NO MORE REQUIRED - SEE wrap BELOW
        //"bScrollAutoCss": true,//NO MORE REQUIRED - SEE wrap BELOW
        "sAjaxSource": "datass.php",
        "aoColumns": colf,
        "bJQueryUI": true,
        "sPaginationType": "two_button",
        "bProcessing": true,
        "bJQueryUI":true,
        "bPaginate": true,
        "table-layout": "fixed",
        "fnServerData": function(sSource, aoData, fnCallback, oSettings) {
            aoData.push({"name": "filters", "value": $.toJSON(getSearchFilters())});//inserisce i filtri
            oSettings.jqXHR = $.ajax({
                "dataType": 'JSON',
                "type": "POST",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            });
        },
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            $(nRow).click(function() {
                $(".row_selected").removeClass("row_selected");
                $(this).addClass("row_selected");
                //mostra il detaglio
                showDetail(aData.CandidateID);
            });
        },
        "fnDrawCallback": function(oSettings) {

        },
        "aaSorting": [[1, 'asc']]
}).wrap("<div style='position:relative;overflow:auto;height:400px;'/>"); //correzione per il disallineamento dello header
2
  • + 1 as this works, but does not quiet solve the problem as I lose the header column scrolling to the bottom of the table.
    – Sydwell
    Feb 18, 2014 at 8:19
  • 1
    I know. Infact I left datatable in a little project in which I have to keep fixed head plus scrollable tbody. I had to create my own table and a custom js
    – alexroat
    Feb 6, 2018 at 23:21
1

Use this: Replace your modal name, clear your datatable and load

$('#modalCandidateAssessmentDetail').on('shown.bs.modal', function (e) {

});
0
1

This is a simple css solution:

.dataTables_scroll {
    overflow:auto;
    display:inline-block
}
1

When the Bootstrap tables is rendered first, you should use the draw event, and then execute columns.adjust():

table.on( 'draw', function () {
    table.columns.adjust();
} );

The draw event is executed when the jquery datatable is already rendered.

columns.adjust() adjusts the size of the columns.

0
0

From linking the answer from Mike Ramsey I eventually found that the table was being initialized before the DOM had loaded.

To fix this I put the initialization function in the following location:

document.addEventListener('DOMContentLoaded', function() {
    InitTables();
}, false);
0

See this solution. It can be solved with a window scroll event firing one time only.

0

I was facing the same issue. I added the scrollX: true property for the dataTable and it worked. There is no need to change the CSS for datatable

jQuery('#myTable').DataTable({
                            "fixedHeader":true,
                            "scrollY":"450px",
                            "scrollX":true,
                            "paging":   false,
                            "ordering": false,
                            "info":     false,
                            "searching": false,
                            "scrollCollapse": true
                            });
1
  • 2
    I started having this problem when I added "scrollX": true
    – Stephen
    Jun 19, 2018 at 17:27
0

I know this is old, but I just ran into the problem and didn't find a great solution. So, I decided on using some js to get the scrollBody's height, as compared to the tables height. If the scrollBody is smaller than the table, then I increase the tables width by 15px to account for the scrollbar. I set this up on resize event too, so that it works when my container changes sizes:

const tableHeight = $('#' + this.options.id).height();
const scrollBodyHeight = $('#' + this.options.id).closest('.dataTables_scrollBody').height();

if (tableHeight > scrollBodyHeight) {
    $('#' + this.options.id).closest('.dataTables_scrollBody').css({
        width: "calc(100% + 15px)",
    })
} else {
    $('#' + this.options.id).closest('.dataTables_scrollBody').css({
        width: "100%",
    })
}
0

$('.DataTables_sort_wrapper').trigger("click");

1
  • Please use the 4-space/tab indentation to make your code formatted like a code block. Probably you should also annotate your code since it's not quite clear how it is related to the problem, where to put it etc. Best regards
    – YakovL
    Sep 6, 2017 at 18:16
0

Unfortunately, none of those solutions worked for me. Perhaps, due to the difference in the initialization of our tables, we have different results. It might be possible, that one of those solutions would work for someone. Anyways, wanted to share my solution, just in case someone is still troubled with this issue. It is a bit hackish, though, but it works for me, since I don't change the width of the table later.

After I load the page and click on the header, so that it expands and shows normally, I inspect the table header and record the width of the .dataTables_scrollHeadInner div. In my case it is 715px, for example. Then add that width to css:

.dataTables_scrollHeadInner
{
  width: 715px !important;
}
0

My solution was add this: ...

initComplete () {
      this.api (). columns (). header (). each ((el, i) => {
          $ (el) .attr ('style', 'min-width: 160px;')
      });
},

...

and it look fine.

0

Gyrocode.com answer to problem was totally correct but his solution will not work in all cases. A more general approach is to add the following outside your document.ready function:

$(document).on( 'init.dt', function ( e, settings ) {
    var api = new $.fn.dataTable.Api( settings );
    window.setTimeout(function () {
            api.table().columns.adjust().draw();
        },1);
} );
0

Add fixed width for container table

JS:

otableCorreo = $("#indexTablaEnvios").DataTable({                
    "fnInitComplete": function (oSettings, json) {
        $(otableCorreo.table().container()).addClass("tablaChildren");
    },
});

CSS:

.tablaChildren {
    width: 97%;
}
0

I had a similar issue. I would create tables in expandable/collapsible panels. As long as the tables were visible, no problem. But if you collapsed a panel, resized the browser, and then expanded, the problem was there. I fixed it by placing the following in the click function for the panel header, whenever this function expanded the panel:

            // recalculate column widths, because they aren't recalculated when the table is hidden'
            $('.homeTable').DataTable()
                .columns.adjust()
                .responsive.recalc();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.