107

I have a problem controlling the width of a table using the jQuery DataTables plugin. The table is supposed to be 100% of the container width, but ends up being an arbitrary width, rather less than the container width.

Suggestions appreciated

The table declaration looks like this

<table id="querytableDatasets" class="display" cellspacing="0"
cellpadding="3"     width="100%">

And the javascript

jQuery('#tab-datasets').load('/cgi-bin/qryDatasets', '', function (){  
    jQuery('#querytableDatasets').dataTable({  
        "bPaginate": false,  
        "bInfo": false,  
        "bFilter": false  
    });  
});  `  

Inspecting the HTML in Firebug, you see this (note the added style="width: 0px;")

<table id="querytableDatasets" class="display" cellspacing="0" 
cellpadding="3" width="100%" style="width: 0px;">

Looking in Firebug at the styles, the table.display style has been overridden. Can't see where this is coming from

element.style {  
  width:0;}    

-- dataTables.css (line 84
table.display { 
  margin:0 auto;  
  width:100%;  
}  
mg1075
  • 17,985
  • 8
  • 59
  • 100
John Mac
  • 2,530
  • 4
  • 24
  • 30
  • FYI, I just encountered an issue where a column was not adjusting correctly in IE8. The culprit was an image that had the `max-width` property set. Apparent IE8 doesn't like that property too much and ignored it in relation to datatables, even though the image was sized correclty on the screen. Changing it to `width` fixed the problem. – John B May 30 '14 at 15:39
  • https://stackoverflow.com/a/46160726/900284 – Frank Myat Thu Dec 16 '22 at 06:13

26 Answers26

71
jQuery('#querytableDatasets').dataTable({  
        "bAutoWidth": false
});
Guido
  • 46,642
  • 28
  • 120
  • 174
Suraj
  • 719
  • 5
  • 2
  • 3
    This was the right answer for me. I'm using boostrap .table-responsive. With the datatable code setting it's own width, it gets in the way. – mac10688 Jan 22 '15 at 15:57
  • Came here to post my solution to this stupid problem which involved removing the width property on the tab change event but this seems to have fixed it. Thanks. +1 – Topher Oct 19 '17 at 16:17
  • I have 3 tabs and datatables on first two tabs, table on second tab was not full width. this fixed my problem. thanks – Mike Volmar Sep 26 '18 at 15:48
61

The issue is caused because dataTable must calculate its width - but when used inside a tab, it's not visible, hence can't calculate the widths. The solution is to call 'fnAdjustColumnSizing' when the tab shows.

Preamble

This example shows how DataTables with scrolling can be used together with jQuery UI tabs (or indeed any other method whereby the table is in a hidden (display:none) element when it is initialised). The reason this requires special consideration, is that when DataTables is initialised and it is in a hidden element, the browser doesn't have any measurements with which to give DataTables, and this will require in the misalignment of columns when scrolling is enabled.

The method to get around this is to call the fnAdjustColumnSizing API function. This function will calculate the column widths that are needed based on the current data and then redraw the table - which is exactly what is needed when the table becomes visible for the first time. For this we use the 'show' method provided by jQuery UI tables. We check to see if the DataTable has been created or not (note the extra selector for 'div.dataTables_scrollBody', this is added when the DataTable is initialised). If the table has been initialised, we re-size it. An optimisation could be added to re-size only of the first showing of the table.

Initialisation code

$(document).ready(function() {
    $("#tabs").tabs( {
        "show": function(event, ui) {
            var oTable = $('div.dataTables_scrollBody>table.display', ui.panel).dataTable();
            if ( oTable.length > 0 ) {
                oTable.fnAdjustColumnSizing();
            }
        }
    } );

    $('table.display').dataTable( {
        "sScrollY": "200px",
        "bScrollCollapse": true,
        "bPaginate": false,
        "bJQueryUI": true,
        "aoColumnDefs": [
            { "sWidth": "10%", "aTargets": [ -1 ] }
        ]
    } );
} );

See this for more info.

Michel Ayres
  • 5,891
  • 10
  • 63
  • 97
Arik Kfir
  • 726
  • 6
  • 3
  • 1
    I also have the same issue with @John McC, however, I applied my datatable to a modal, i'm using bootstrap and I got stuck with this issue..do you know how to implement it using bootstrap modal instead of tabs?..i really need your help – cfz Sep 23 '13 at 10:20
  • i recommend to use `window.resize`, look a example https://legacy.datatables.net/ref#fnAdjustColumnSizing – KingRider Nov 23 '16 at 18:58
  • "aoColumnDefs": [{ "sWidth": "10%", "aTargets": [ -1 ] }]. I fix my problem just add this, thank you. – Mina chen Nov 12 '19 at 02:58
55

You'll want to tweak two variables when you initialize dataTables: bAutoWidth and aoColumns.sWidth

Assuming you have 4 columns with widths of 50px, 100, 120px and 30px you would do:

jQuery('#querytableDatasets').dataTable({  
        "bPaginate": false,  
        "bInfo": false,  
        "bFilter": false,
        "bAutoWidth": false,
        "aoColumns" : [
            { sWidth: '50px' },
            { sWidth: '100px' },
            { sWidth: '120px' },
            { sWidth: '30px' }
        ]  
    }); 

More information on the initialization of dataTables can be found at http://datatables.net/usage

Watch for interaction between this setting of widhts and the CSS you are applying. You might comment your existing CSS before trying this to see how close you get.

artlung
  • 33,305
  • 16
  • 69
  • 121
  • mmm. is what you're saying is that this is a result of bAutoWidth:true making not particularly intelligent choices for column width. – John Mac Mar 16 '09 at 22:04
  • This is what I think. My tables bounce around if the data is inconsistent in length. This is why I put in the aoColumns and bAutoWidth parameters. – artlung Mar 19 '09 at 17:15
  • 1
    beautiful. totally fixed my issue. – Laguna Jan 31 '12 at 19:58
  • Awesome @Laguna! Love hearing that old answers like this keep being helpful. – artlung Jan 31 '12 at 20:36
  • 1
    "bAutoWidth": false works. But just a question. Is it a good practice or not if I put width details on my tags? – finnTheHumin Oct 16 '13 at 06:23
  • @finnTheHuman I think that's a valid practice, and is efficient, presuming it actually works across your target browsers for controlling the widths of your columns as you like. You can also look at `` and `` tags for controlling column widths. Many choices for formatting table column widths. I like to go with less markup where possible. – artlung Oct 16 '13 at 18:09
49

Well, I'm not familiar with that plugin, but could you reset the style after adding the datatable? Something like

$("#querydatatablesets").css("width","100%")

after the .dataTable call?

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • 1
    I have found this to be the best solution as well, because in my case, the table was also being set to 100px width when any of the columns was made invisible - see here: http://www.datatables.net/forums/discussion/3417/table-gets-width0px-when-bvisiblefalse-is-used/p1 – mydoghasworms Aug 02 '11 at 12:41
  • This is the solution that worked for me. it gives finer control over the css of the data table compared to the oTable.fnAdjustColumnSizing(); solution mentioned earlier. – Vijay Rumao Jul 09 '15 at 19:35
14

I have had numerous issues with the column widths of datatables. The magic fix for me was including the line

table-layout: fixed;

this css goes with the overall css of the table. For example, if you have declared the datatables like the following:

LoadTable = $('#LoadTable').dataTable.....

then the magic css line would go in the class Loadtable

#Loadtable {
margin: 0 auto;
clear: both;
width: 100%;
table-layout: fixed;

}

user1842675
  • 261
  • 4
  • 10
  • 2
    This helps, but now my columns are all strange sizes. I would have expected that the columns with the most data would take the largest percentage width. – cjbarth Nov 19 '13 at 11:46
  • This fails when your table has horizontal scrolling. – Rabby Feb 04 '21 at 15:30
7

TokenMacGuys solution works best becasue this is the result of a bug in jQdataTable. What happens is if you use $('#sometabe').dataTable().fnDestroy() the table width gets set to 100px instead of 100%. Here is a quick fix:

$('#credentials-table').dataTable({
        "bJQueryUI": false,
        "bAutoWidth": false,
        "bDestroy": true,
        "bPaginate": false,
        "bFilter": false,
        "bInfo": false,
    "aoColumns": [
           { "sWidth": "140px" },
           { "sWidth": "300px" },
           { "sWidth": "50px" }       
        ],
        "fnInitComplete": function() {

            $("#credentials-table").css("width","100%");
        }

    });
Peter Drinnan
  • 4,344
  • 1
  • 36
  • 29
6

You have to leave at least one field without fixed field, for example:

$('.data-table').dataTable ({

 "bAutoWidth": false,
 "aoColumns" : [
    null,
    null,
    null,                    
    null,
    {"sWidth": "20px"},
    { "sWidth": "20px"}]
});

You can change all, but leave only one as null, so it can stretch. If you put widths on ALL it will not work. Hope I helped somebody today!

cure85
  • 441
  • 5
  • 6
6

As on Datatable 10.1, this is straight forward. Just put width attribute to your table in HTML. i.e. width="100%", this will override all CSS styles set by DT.

See this http://www.datatables.net/examples/basic_init/flexible_width.html

Udit
  • 659
  • 6
  • 2
6

Add this css class to your page, it will fix the issue:

#<your_table_id> {
    width: inherit !important;
}
Bahadir Tasdemir
  • 10,325
  • 4
  • 49
  • 61
5

Setting widths explicitly using sWidth for each column AND bAutoWidth: false in dataTable initialization solved my (similar) problem. Love the overflowing stack.

axel22
  • 32,045
  • 9
  • 125
  • 137
tubelight
  • 51
  • 1
  • 3
4
"fnInitComplete": function() {
    $("#datatables4_wrapper").css("width","60%");
 }

This worked fine to adjust the whole table width. Thanks @Peter Drinnan!

Nilani Algiriyage
  • 32,876
  • 32
  • 87
  • 121
  • I could not get the table to properly fill its parent container. Tried adjusting css of the table and its wrapper to width:100%; with no noticeable difference. Once i tried the above mentioned method it worked wonders, however im not pointing to the wrapper, instead i had to point to the table it's self. But big thanks Nilani!! – Logic1 Feb 18 '15 at 22:02
3

None of the solutions here worked for me. Even the example on the datatables homepage did not work hence to the initialization of the datatable in the show option.

I found a solution to the problem. The trick is to use the activate option for tabs and to call fnAdjustColumnSizing() on the visible table:

$(function () {

// INIT TABS WITH DATATABLES
$("#TabsId").tabs({
    activate: function (event, ui) {
        var oTable = $('div.dataTables_scrollBody>table:visible', ui.panel).dataTable();
        if (oTable.length > 0) {
            oTable.fnAdjustColumnSizing();
        }
    }
});

// INIT DATATABLES
// options for datatables
var optDataTables = {
    "sScrollY": "200px",
    "bScrollCollapse": true,
    "bPaginate": false,
    "bJQueryUI": true,
    "aoColumnDefs": [
        { "sWidth": "10%", "aTargets": [-1] }
    ]
};
// initialize data table
$('table').dataTable(optDataTables);

});
2

Just to say I've had exactly the same problem as you, although I was just apply JQuery to a normal table without any Ajax. For some reason Firefox doesn't expand the table out after revealing it. I fixed the problem by putting the table inside a DIV, and applying the effects to the DIV instead.

Dave
  • 21
  • 1
2

Are you doing this in the ready event?

$(document).ready(function() { ... });

The sizing is most likely going to be dependent on the document being fully loaded.

Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
Mufaka
  • 2,333
  • 1
  • 18
  • 25
  • take a the code look above - it's happening in the callback from the ajax load of the div container #tab-datasets. Table #querytableDatasets is provided by /cgi-bin/qryDatasets – John Mac Mar 03 '09 at 23:04
  • I understand that, I'm not sure of the timing for that happening. In looking at the plugin source, it seemed like the only time it could set a 0px width is when it couldn't determine the correct table offSetWidth and I figured that was related to running too early. – Mufaka Mar 04 '09 at 00:24
  • hmm. I've assumed that the callback from the ajax load is called after the table #querytableDatasets is loaded. do you think that this may not be the case? – John Mac Mar 04 '09 at 06:08
  • BTW to answer your question about when this runs, it's in response to the user clicking a button – John Mac Mar 04 '09 at 06:09
  • Hmm, not sure I can add anything more then. If it's a button click, then the document is fully loaded and there is no reason to put this in the ready event. You might play around with the width of the table's container or try to get their (DataTables plugin) working outside of your current layout. – Mufaka Mar 05 '09 at 00:23
2

Check this solution too. this solved my DataTable column width issue easily

JQuery DataTables 1.10.20 introduces columns.adjust() method which fix Bootstrap toggle tab issue

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

Please refer the documentation : Scrolling and Bootstrap tabs

PNP
  • 361
  • 5
  • 17
1

For anyone having trouble adjusting table / cell width using the fixed header plugin:

Datatables relies on thead tags for column width parameters. This is because its really the only native html as most of the table's inner html gets auto-generated.

However, what happens is some of your cell can be larger than the width stored inside the thead cells.

I.e. if your table has a lot of columns (wide table) and your rows have a lot of data, then calling "sWidth": to change the td cell size won't work properly because the child rows are automatically resizing td's based on overflow content and this happens after the table's been initialized and passed its init params.

The original thead "sWidth": parameters get overridden (shrunk) because datatables thinks your table still has its default width of %100--it doesn't recognize that some cells are overflowed.

To fix this I figured out the overflow width and accounted for it by resizing the table accordingly after the table has been initialized--while we're at it we can init our fixed header at the same time:

$(document).ready(function() {
  $('table').css('width', '120%');
  new FixedHeader(dTable, {
        "offsetTop": 40,
      });
});
DrewT
  • 4,983
  • 2
  • 40
  • 53
1

create your fixedheader inside the "success" of your ajax call, you will not have any alignment problem in header and rows.

success: function (result) {
              /* Your code goes here */

    var table = $(SampleTablename).DataTable();

        new $.fn.dataTable.FixedHeader(table);
}        
Chen-Tsu Lin
  • 22,876
  • 16
  • 53
  • 63
1

Hope this helps someone who's still struggling.

Don't keep your table inside any container. Make the table's wrapper your container after the table's rendered. I know this might be invalid at places where you have something else along with the table but then you could always append that content back.

For me,this problem arises if you have a sidebar and a container that is actually an offset to that sidebar.

$(YourTableName+'_wrapper').addClass('mycontainer');

(I added a panel panel-default)
And your class :

.mycontainer{background-color:white;padding:5px;}
1

find another useful link about this problem and it resolved my problem.

<table width="100%">
<tr>
    <td width="20%"> Left TD <td>
    <td width="80%"> Datatable </td>
</tr>
</table>

Datatables force width table

Community
  • 1
  • 1
0

i had the similar problem and found that text in columns don't break and using this css code solved the problem

th,td{
max-width:120px !important;
word-wrap: break-word
}
h0mayun
  • 3,466
  • 31
  • 40
0

This is my way of doing it..

$('#table_1').DataTable({
    processing: true,
    serverSide: true,
    ajax: 'customer/data',
    columns: [
        { data: 'id', name: 'id' , width: '50px', class: 'text-right' },
        { data: 'name', name: 'name' width: '50px', class: 'text-right' }
    ]
});
Kevin Khew
  • 471
  • 5
  • 11
0

I Meet the same problem today.

I used a tricky way to solve it.

My Code as below.

$('#tabs').tabs({
    activate: function (event, ui) {
       //redraw the table when the tab is clicked
       $('#tbl-Name').DataTable().draw();
    }
});
Regolith
  • 2,944
  • 9
  • 33
  • 50
0

I ran into a similar issue when having a div wrapped around the table.

Adding position: relative fixed it for me.


#report_container {
 float: right;
 position: relative;
 width: 100%;
}
mardala
  • 237
  • 1
  • 4
0

I had a similar issue where the contents of the table were bigger than the table header and footer. Adding a div around the table and setting x-overflow seems to have sorted this issue:

Nick Holden
  • 3,639
  • 3
  • 22
  • 12
0

Be sure that all others parameters before bAutoWidth & aoColumns are correctly entered.Any wrong parameter before will break this functionality.

DejanR
  • 441
  • 4
  • 11
-1

This works fine.

#report_container {
   float: right;
   position: relative;
   width: 100%;
}
Sam
  • 376
  • 3
  • 10