Specifying a fixed column width in jQuery Datatables

馋奶兔 提交于 2019-11-28 20:50:48

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/.

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.

for the <table> tag or its css class or css id add the following style:

`table{
     margin: 0 auto;
     width: 100%;
     clear: both;
     border-collapse: collapse;
     table-layout: fixed;
     word-wrap:break-word;
}`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!