How to center align datatables header

前端 未结 4 1853
渐次进展
渐次进展 2021-02-19 23:32

I\'m new to datatables. When I make table header, it\'s always left align. How can I set the header to center align? I\'ve read datatables.net/manual/styling/classes and datatab

4条回答
  •  别那么骄傲
    2021-02-20 00:16

    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

提交回复
热议问题