How to center align datatables header

前端 未结 4 1934
渐次进展
渐次进展 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:12

    by using this style :

    table.center-all td,th{
        text-align :center;
    }
    

    I can add the center-all class to my table and everything will be aligned to center. like this :

    <table class="center-all">
        ....
    </table
    

    In this way I have the option to center the content of some tables without need to apply it to the whole page/site

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-20 00:18

    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;
    }
    
    0 讨论(0)
  • 2021-02-20 00:25

    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;}
    
    0 讨论(0)
提交回复
热议问题