简体   繁体   中英

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
});

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 offautoWidth 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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM