usr4896260
usr4896260

Reputation: 1507

jquery datatable set width upon initialization

I'm trying to set the width of a cell in a jQuery datatable upon initialization and it never seems to work. I've have tried what the official site recommends and other examples. Below are some of the options I have tried. Please help on what I'm doing wrong?

Ex: 1

$('#dataTables-comments').DataTable({
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "aoColumns": [{
            "sWidth": "50%"
        }, 
        {
            "sWidth": null
        },  
        {
            "sWidth": null
        },   
        {
            "sWidth": null
        },   
        {
            "sWidth": null
        }   
    ],
    "responsive": true
});

Ex: 2

$('#dataTables-tbl').DataTable({
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "columnDefs": [{
        "width": "50%",
        "targets": 0
    }],
    "responsive": true
});

Ex: 3

$('#dataTables-tbl').DataTable({
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "columns": [{
        "width": "50%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }],
    "responsive": true
});

Upvotes: 1

Views: 1006

Answers (1)

davidkonrad
davidkonrad

Reputation: 85538

As with any other usage of a CSS percentage value, the value must be a percentage of something. If the table itself not have a defined width, then 10% is untranslatable. So give your table a width :

#dataTables-comments {
  width: 800px;
}

and be sure to turn off autoWidth so dataTables not begin to overrule the predefined column widths :

$('#dataTables-tbl').DataTable({
    autoWidth: false, //<---
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "columns": [{
        "width": "50%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }],
    "responsive": true
});

Upvotes: 1

Related Questions