在 html 中,可以使用三种方法使表格居中:使用 margin: auto; 属性使表格水平居中。使用 text-align: center; 属性在父元素内垂直居中表格。使用 align 属性指定表格相对于父元素的位置(弃用)。
如何让 HTML 表格居中
在 HTML 中,有几种方法可以使表格居中:
1. 使用 margin: auto;
给表格设置 margin: auto; 属性,可以让表格在水平方向上居中。
示例:
<code class="html"><table style="margin: auto;">
<tr>
<th>列 1</th>
<th>列 2</th>
</tr>
<tr>
<td>数据 1</td>
<td>数据 2</td>
</tr>
</table></code>
登录后复制
2. 使用 text-align: center;
给表格的父元素设置 text-align: center; 属性,可以让表格在父元素内垂直居中。
示例:
<code class="html"><div style="text-align: center;">
<table border="1">
<tr>
<th>列 1</th>
<th>列 2</th>
</tr>
<tr>
<td>数据 1</td>
<td>数据 2</td>
</tr>
</table>
</div></code>
登录后复制
3. 使用 align 属性
给表格设置 align 属性,可以指定表格相对于其父元素的位置。
示例:
<code class="html"><table align="center">
<tr>
<th>列 1</th>
<th>列 2</th>
</tr>
<tr>
<td>数据 1</td>
<td>数据 2</td>
</tr>
</table></code>
登录后复制
注意:
align 属性在 HTML5 中已弃用,应优先使用 margin 或 text-align 属性。
如果为表格设置了宽度,则居中效果可能会受到影响。
以上方法均可用于让表格在水平或垂直方向上居中。






