Bootstrap表格内容居中技巧:使用text-center类实现水平居中(table-centered类名应用于th和td元素)。使用d-flex和align-items-center类垂直对齐内容,并设置div高度匹配行高(适用于固定行高的表格)。

Bootstrap 表格内容居中:提升表格可读性
在 Bootstrap 表格中,内容居中是改善表格可读性和美观性的有效方法。通过 CSS 样式,可以轻松地将表格内容水平居中或垂直居中。
水平居中
要水平居中表格内容,请使用 text-center 类:
<code class="css">.table-centered {
text-align: center;
}</code>然后将其应用于 <th> 和 <td> 元素:
<code class="html"><table class="table-centered">
<tr>
<th>头 1</th>
<th>头 2</th>
...
</tr>
<tr>
<td>数据 1</td>
<td>数据 2</td>
...
</tr>
</table></code>垂直居中
垂直居中表格内容需要更多步骤:
- 创建一个额外的
<div>元素并将其包裹在<th>或<td>中。 - 为这个
<div>元素应用d-flex和align-items-center类,以垂直对其内容。 - 设置
<div>的高度以匹配行高。
例如:
<code class="html"><table>
<tr>
<th>
<div class="d-flex align-items-center" style="height: 50px;">
头 1
</div>
</th>
...
</tr>
...
</table></code>要自定义高度,只需调整 style="height: 50px;" 中的值即可。
注意:
- 垂直居中仅适用于固定行高的表格。
- 如果表格内容包含元素(例如按钮或图像),请使用适当的 CSS 规则来使其水平或垂直居中。









