DataTables Align Text Using columnDefs
DataTables Align Text Using columnDefs
Ninja Joe
Posts: 15Questions: 7Answers: 1
in DataTables
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
You are applying both
dt-center
anddt-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 usedifferent
-option columnDefs.targets, like classname on the
-tag thfor the
dt-center` class that doesn't get applied to column 12.You could also remove the
dt-center
class from column 12 using jQuery ininitComplete
.Kevin
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.
This has duplicate keys of
className
and is probably not working as expected. You probably should do something like this:Kevin
Very nice suggestion! I'm all for more succinct code. I updated my code. Thanks again.