讓表格在容器中垂直置中,曾經需要嵌套表格 Hack,現代 CSS 提供優雅的標準解法。本文對比新舊方案並給出最佳實踐。
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" valign="middle">
<table>
<tr><td>垂直置中內容</td></tr>
</table>
</td>
</tr>
</table>
原理:外層表格撐滿視口,td 的 valign="middle" 實現垂直置中。缺點:語義混淆、代碼冗余、難維護。
.v-center-container {
display: flex;
align-items: center; /* 垂直置中 */
justify-content: center; /* 水平置中 */
min-height: 100vh; /* 至少視口高度 */
}
<div class="v-center-container">
<table>
<tr><td>內容完美置中</td></tr>
</table>
</div>
.v-center-grid {
display: grid;
place-items: center; /* 同時垂直水平置中 */
min-height: 100vh;
}
.v-center-absolute {
position: relative;
min-height: 100vh;
}
.v-center-absolute table {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<style>
.table-v-center td,
.table-v-center th {
vertical-align: middle; /* middle | top | bottom | baseline */
padding: 16px;
}
</style>
<table class="table-v-center">
<tr>
<td style="height: 100px">垂直置中</td>
<td>預設 baseline</td>
</tr>
</table>
| 場景 | 推薦方案 | 支援度 |
|---|---|---|
| 現代專案、全瀏覽器 | Flexbox / Grid | IE10+ / 全部現代 |
| IE9 相容專案 | 絕對定位 + Transform | IE9+ |
| HTML Email | 嵌套表格 + valign | 所有郵件客戶端 |
| 儲存格內垂直對齊 | vertical-align: middle | 所有瀏覽器 |
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表格垂直置中 Demo</title>
<style>
.page-center {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 20px;
box-sizing: border-box;
}
.data-table {
border-collapse: collapse;
width: 100%;
max-width: 600px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.data-table th,
.data-table td {
border: 1px solid #e0e0e0;
padding: 12px 16px;
vertical-align: middle;
}
.data-table thead { background: #f5f5f5; }
</style>
</head>
<body>
<div class="page-center">
<table class="data-table">
<thead><tr><th>項目</th><th>數值</th></tr></thead>
<tbody>
<tr><td>收入</td><td>$1,234,567</td></tr>
<tr><td>支出</td><td>$890,123</td></tr>
</tbody>
</table>
</div>
</body>
</html>
拋棄嵌套表格,擁抱現代 CSS 佈局,代碼更乾淨、語義更清晰、維護更輕鬆。