在表格儲存格中實現文字縮進、對齊與留白控制,應使用 CSS `text-indent`、`padding`、`text-align` 等屬性,而非 HTML 已廢棄的 `align`、`valign` 或空白字元。本文說明各屬性適用場景、常見誤區與完整範例,助你精準控制表格內文字排版。
| 需求 | CSS 屬性 | 適用選擇器 | 說明 |
|---|---|---|---|
| 首行縮進 | text-indent | `td`, `th` | 僅影響第一行,單位建議用 `em`(相對字體大小) |
| 儲存格內邊距(四周留白) | padding | `td`, `th` | 推薦控制文字與邊框距離,取代舊 `cellpadding` |
| 水平對齊 | text-align | `td`, `th` | `left`/`center`/`right`/`justify` |
| 垂直對齊 | vertical-align | `td`, `th` | `top`/`middle`/`bottom`/`baseline`,僅對 `table-cell` 生效 |
| 文字換行控制 | white-space, `word-break`, `overflow-wrap` | `td`, `th` | 防止長英文/URL 撐破版面 |
<style>
.indent-table td {
padding: 10px 16px;
border: 1px solid #ddd;
}
.indent-table td.content {
text-indent: 2em; /* 縮進 2 個字元寬度 */
text-align: justify; /* 兩端對齊,配合縮進效果佳 */
}
</style>
<table class="indent-table">
<tr>
<th>章節</th>
<th>內容</th>
</tr>
<tr>
<td>1.1</td>
<td class="content">HTML(HyperText Markup Language)是構建網頁的標準標記語言。它使用標籤來描述文件的結構與語意...</td>
</tr>
<tr>
<td>1.2</td>
<td class="content">CSS(Cascading Style Sheets)用於控制網頁的外觀與排版,實現結構與表現分離...</td>
</tr>
</table>
.prose-table td.content {
/* 基礎縮進 */
text-indent: 2em;
/* 防止長英文/數字撐破 */
word-break: break-word;
overflow-wrap: break-word;
/* 行高優化閱讀 */
line-height: 1.8;
}
/* 小螢幕減少縮進 */
@media (max-width: 480px) {
.prose-table td.content { text-indent: 1.5em; }
}
/* 列印樣式:縮進改為 2em,確保紙本閱讀習慣 */
@media print {
.prose-table td.content { text-indent: 2em; }
}
<style>
.vcenter-table {
border-collapse: collapse;
width: 100%;
}
.vcenter-table th,
.vcenter-table td {
border: 1px solid #ddd;
padding: 12px 16px;
vertical-align: middle; /* 關鍵:垂直置中 */
}
.vcenter-table th {
background: #f5f5f5;
font-weight: 600;
}
/* 圖片/圖示垂直置中輔助 */
.vcenter-table img,
.vcenter-table .icon {
vertical-align: middle;
margin-right: 8px;
}
</style>
<table class="vcenter-table">
<tr>
<th>項目</th>
<th>說明</th>
</tr>
<tr>
<td><img src="icon.png" width="24" height="24" alt="">儀表板</td>
<td>系統總覽儀表板,包含即時監控指標...</td>
</tr>
<tr>
<td><span class="icon">📊</span>報表</td>
<td>多維度資料視覺化報表匯出功能...</td>
</tr>
</table>
表格文字排版核心原則:語意用 HTML(` 避免使用 ` `、`align`、`valign`、`margin` 等舊寫法,建立專案通用的表格排版 CSS 模組,確保一致性與維護效率。`、` `、`
- 首行縮進 → `text-indent: 2em`
- 內邊距 → `padding: 12px 16px`
- 水平對齊 → `text-align: left/center/right`
- 垂直對齊 → `vertical-align: middle`
- 響應式調整 → Media Query 微調 `text-indent`、`padding`、`font-size`
HTML5 教學排行
推薦文章