如何将Datatables表头居中对齐

19

我是datatables的新手。当我制作表头时,它总是左对齐的。我该如何将表头设置为居中对齐?我已经阅读了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。你能否制作一个可工作的代码片段,以便我们可以提出建议? - Praveen Kumar Purushothaman
4个回答

19

楼主,你已经非常接近解决方案了,只是在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


17

如果在HTML中指定了类名后发现样式没有生效,可能是因为您需要在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是不必要的,因为它已经在datatables中了。 - Fred Andrews

4
你可以使用CSS实现这一点。只需将你的表格类作为选择器,然后针对该选择器内的每个表格标题进行目标定位,如下所示:
.table th {
  text-align: center;
}

2
通过使用这种样式:
table.center-all td,th{
    text-align :center;
}

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

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

这样我就可以选择将某些表格的内容居中,而不需要将其应用于整个页面/网站。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接