【问题标题】:How to center align datatables header如何居中对齐数据表标题
【发布时间】:2016-10-29 15:00:41
【问题描述】:

我是数据表的新手。当我制作表格标题时,它总是左对齐。 如何将标题设置为居中对齐? 我已经阅读了 datatables.net/manual/styling/classes 和 datatables.net/reference/option/columns.className 但仍然不知道如何实现它。

$('.table').DataTable({
  "paging": true,
  "lengthChange": true,
  "searching": true,
  "ordering": true,
  "info": true,
  "language": {
    "url": "http://cdn.datatables.net/plug-ins/1.10.9/i18n/Indonesian.json"
  }
  "columnDefs": {
    {
      className: "dt-head-center"
    }
  }
});

【问题讨论】:

  • 你需要使用 CSS。您能否制作一个有效的 sn-p 以便我们提出建议?

标签: jquery html css datatables


【解决方案1】:

OP,您非常接近解决方案,只是缺少 columnDefs 中的 targets 选项以将 dt-head-center 类分配给您要设置样式的标题。

// apply to columns 1 & 2
targets: [ 0, 1 ]

CSS 是一个选项,但不是必需的。

我喜欢 DataTables 建议的使用 column.className 选项设置单元格样式的方法,然后使用 targets 应用它们。 https://datatables.net/reference/option/columns.className 与全局 CSS 应用程序相比,这为我们提供了更精细的控制级别。

这将分别对齐标题和正文内容:

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 ] }
]

或同时对齐它们:

columnDefs: [
   // Center align both header and body content of columns 1, 2 & 3
   { className: "dt-center", targets: [ 0, 1, 2 ] }
]

单元格类格式:

dt[-head|-body][-left|-center|-right|-justify|-nowrap]

有关 DataTables 单元类的更多信息:https://datatables.net/manual/styling/classes#Cell-classes

【讨论】:

    【解决方案2】:

    你可能在指定类后忘记了,需要在 CSS 中添加以下内容:

    .dt-head-center {text-align: center;}
    

    此外,如果该类尚未添加到表的 <th> 中,请尝试为通用内容添加以下 CSS:

    thead, th {text-align: center;}
    
    /* OR */
    
    .table thead,
    .table th {text-align: center;}
    

    要使其特定于特定表格,您可以给表格一个id="tableID",然后在 CSS 中,您可以这样做:

    #tableID thead,
    #tableID th {text-align: center;}
    

    【讨论】:

    • 我发现只要确保类在标题上就足够了。添加额外的 CSS 是不必要的,因为它已经在数据表中。
    【解决方案3】:

    您可以使用 CSS 来做到这一点。只需将您的表格类用作选择器并定位该选择器内的每个表格标题,如下所示:

    .table th {
      text-align: center;
    }
    

    【讨论】:

      【解决方案4】:

      通过使用这种风格:

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

      我可以将center-all 类添加到我的表中,所有内容都将对齐到中心。像这样:

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

      通过这种方式,我可以选择将某些表格的内容居中而不需要将其应用于整个页面/站点

      【讨论】:

        猜你喜欢
        • 2017-08-28
        • 1970-01-01
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 2014-10-13
        • 1970-01-01
        • 1970-01-01
        • 2018-05-01
        相关资源
        最近更新 更多