Specifying a fixed column width in jQuery Datatables

Here is a code sample (fixed the column width for 4 column table):

  1. set autoWidth: false;
  2. set px values to first 3 columns;
  3. important: check if the table width is a bit more than 3 columns + final one;
  4. adjust the table width and 4th column.

    $('#example').DataTable({ //four column table
       autoWidth: false, //step 1
       columnDefs: [
          { width: '300px', targets: 0 }, //step 2, column 1 out of 4
          { width: '300px', targets: 1 }, //step 2, column 2 out of 4
          { width: '300px', targets: 2 }  //step 2, column 3 out of 4
       ]
    });
    

Set table width, 4*300px:

     #example { width: 1200px };

As result you will see 1st 3 columns with 300px width and the final one will be flexible and about 150px (which requires additional adjusting).


Last but not least: fixed column size 300px will not prevent you from the case when cell contains a too long (> 300px without spaces) word. So you have to keep in mind that all words must be less than the fixed side of your column.


This is not a DataTables issue. See how column widths are determined. Based on this algorithm I see the following two solutions.

Solution 1

Calculate yourself the table width and set it accordingly.

#example {
  width: 3562px;
}

See live example here: http://jsfiddle.net/cdog/jsf6cg6L/.

Solution 2

Set the minimum content width (MCW) of each cell and let the user agent to determine the column widths.

To do this, add classes to the target columns to be able to style them:

var table = $('#example').DataTable({
  tabIndex: 8,
  dom: '<"fcstTableWrapper"t>lp',
  bFilter: false,
  bAutoWidth: false,
  data: [],
  columnDefs: [{
    class: 'details-control',
    orderable: false,
    data: null,
    defaultContent: '',
    targets: 0
  }, {
    targets: 1
  }, {
    class: 'col-2',
    targets: 2
  }, {
    class: 'col-3',
    targets: 3
  }, {
    targets: 4
  }, {
    targets: 'dlySlsFcstDay'
  }, {
    targets: 'dlySlsFcstWkTtl'
  }],
  order: [[1, 'asc']]
});

Then set the desired value of the minimum width property for each class:

.col-2,
.dlySlsFcstWkTtl {
  min-width: 60px;
}

.col-3 {
  min-width: 1100px;
}

See live example here: http://jsfiddle.net/cdog/hag7Lpm5/.