如何居中对齐数据表头

时间:2016-06-27 14:30:25

标签: jquery html css 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"
    }
  }
});

4 个答案:

答案 0 :(得分:6)

您可能在指定类后忘记了,您需要在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;}

答案 1 :(得分:3)

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

.table th {
  text-align: center;
}

答案 2 :(得分:3)

OP,您非常接近解决方案,只是错过targets中的columnDefs选项,将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 ] }
]

Cell class格式:

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

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

答案 3 :(得分:1)

使用这种风格:

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

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

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

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