DataTables Align Text Using columnDefs

DataTables Align Text Using columnDefs

Ninja JoeNinja Joe Posts: 15Questions: 7Answers: 1

I'm using DataTables in my app and it works great. To center the text, I'm using:

{ className: 'dt-center', targets: '_all' },

However, for the last column, I want to align the text left instead of center, but the following is having no effect:

{ targets: [ 12 ], className: 'dt-left' }

Here is my complete code:

$('#audits-datatable').DataTable({
    columnDefs: [
        { width: '70px', targets: [ 0, 1, 11 ] },
        { width: '125px', targets: [ 8 ] },
        { width: '600px', targets: [ 12 ] },
        { className: 'dt-center', targets: '_all' },
        { targets: [ 12 ], className: 'dt-left' }
    ],
});

Why is "dt-left" not overriding "dt-center" in column 12? It still shows up aligned centered instead of left.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951
    edited March 2022 Answer ✓

    You are applying both dt-center and dt-left to column 12. Maybe if you reverse lines 6 and 7 you will get the results you want. A better (more reliable) option might be to use different-option columnDefs.targets, like classname on the-tag thfor thedt-center` class that doesn't get applied to column 12.

    You could also remove the dt-center class from column 12 using jQuery in initComplete.

    Kevin

  • Ninja JoeNinja Joe Posts: 15Questions: 7Answers: 1

    Your first suggestion of reversing lines 6 and 7 worked; however, it only worked for the table body, not the table header. For the table header, I needed to add className: 'dt-head-left'.

    Final code that worked for me:

    $('#audits-datatable').DataTable({
    columnDefs: [
    { width: '70px', targets: [ 0, 1, 11 ] },
    { width: '125px', targets: [ 8 ] },
    { width: '600px', targets: [ 12 ] },
    { targets: [ 12 ], width: '650px', className: 'dt-left', className: 'dt-head-left' },
    { targets: '_all', className: 'dt-center' }
    ],
    });

    Thanks for your help. <3

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951
    { targets: [ 12 ], width: '650px', className: 'dt-left', className: 'dt-head-left' },
    

    This has duplicate keys of className and is probably not working as expected. You probably should do something like this:

    { targets: [ 12 ], width: '650px', className: 'dt-left dt-head-left' },
    

    Kevin

  • Ninja JoeNinja Joe Posts: 15Questions: 7Answers: 1

    Very nice suggestion! I'm all for more succinct code. :) I updated my code. Thanks again.

Sign In or Register to comment.