在 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 屬性。
如果為表格設置了寬度,則居中效果可能會受到影響。
以上方法均可用于讓表格在水平或垂直方向上居中。






