How to center align datatables header
You can do this with CSS. Just use your table class as a selector and target every table heading inside that selector, like this:
.table th {
text-align: center;
}
You might have forgotten after specifying the class, you need to add the following in CSS:
.dt-head-center {text-align: center;}
Also, if the class has not been added to the <th>
of the table, try adding the below CSS for generic stuff:
thead, th {text-align: center;}
/* OR */
.table thead,
.table th {text-align: center;}
To make it specific to a particular table, you can give the table an id="tableID"
and then in the CSS, you can do:
#tableID thead,
#tableID th {text-align: center;}
OP, you were super close to the solution, just missing the targets
option in columnDefs
to assign the dt-head-center
class to the header you want to style.
// apply to columns 1 & 2
targets: [ 0, 1 ]
CSS is an option but not necessary.
I like the DataTables suggested method of using the column.className
option for the styling of cells then apply them using targets
. https://datatables.net/reference/option/columns.className This gives us a finer level of control as opposed to a global CSS application.
This will align header and body content individually:
columnDefs: [
// Center align the header content of column 1
{ className: "dt-head-center", targets: [ 0 ] },
// Center align the body content of columns 2, 3, & 4
{ className: "dt-body-center", targets: [ 1, 2, 3 ] }
]
or align them both at the same time:
columnDefs: [
// Center align both header and body content of columns 1, 2 & 3
{ className: "dt-center", targets: [ 0, 1, 2 ] }
]
Cell class format:
dt[-head|-body][-left|-center|-right|-justify|-nowrap]
More info on DataTables cell classes: https://datatables.net/manual/styling/classes#Cell-classes