HTML 表格結構層級深(table > thead/tbody > tr > th/td),缺乏縮排會導致標籤巢狀關係難以辨識、修改易出錯、Code Review 低效。良好的縮排規範是團隊協作品質的基石。
現代專案多採 **2 空格**(Vue、React 社群慣例)或 **4 空格**(傳統企業專案),團隊統一即可,**禁用混合**。
<table class="data-table">
<caption>使用者列表</caption>
<colgroup>
<col style="width: 60px;">
<col style="width: 200px;">
<col>
</colgroup>
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">姓名</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>張三</td>
<td>zhang@example.com</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
<td>li@example.com</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">共 2 筆資料</td>
</tr>
</tfoot>
</table>
| 風格 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 多行(推薦) | 清晰可讀、易 Diff、易加註解 | 檔案較大 | 手寫模板、伺服器端渲染、團隊協作 |
| 單行壓縮 | 檔案小、傳輸快 | 難讀、難維護、Diff 雜訊大 | 建置輸出、CDN 快取、生產環境 |
| 混合:表頭多行、資料單行 | 平衡可讀與體積 | 風格不一致 | 大量資料表格 |
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[html]": {
"editor.tabSize": 2,
"editor.insertSpaces": true
},
"prettier.tabWidth": 2,
"prettier.useTabs": false,
"prettier.htmlWhitespaceSensitivity": "css",
"prettier.singleQuote": true,
"prettier.printWidth": 120
}
{
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"printWidth": 120,
"htmlWhitespaceSensitivity": "css",
"endOfLine": "lf"
}
// .htmlhintrc
{
"indent": 2,
"indent-style": "space",
"tagname-lowercase": true,
"attr-lowercase": true,
"attr-value-double-quotes": true,
"doctype-first": true,
"spec-char-escape": true,
"id-class-value": "dash",
"src-not-empty": ["img", "input", "textarea"]
}
{/* ❌ 錯誤:模板邏輯破壞縮排 */}
<table>
<tbody>
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{/* ✅ 正確:邏輯另起行,內容保持縮排 */}
<table>
<tbody>
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- /header -->, <!-- /tbody:user-list --><tbody> 分組(如每群組一個 tbody)<th scope="col">、<td data-id="123"> 寫在前面<td
class="status-cell"
data-status="active"
data-user-id="12345"
aria-label="使用者狀態:啟用"
>
啟用
</td>
<!-- 建置流程 -->
html-minifier-terser --collapse-whitespace --remove-comments --minify-css --minify-js
// 輸出單行最小化 HTML
<!-- 開發環境保留格式,生產環境壓縮 -->
// Source Map 對應原始縮排位置(HTML 少見,JS/CSS 常用)
表格縮排不是美觀問題,而是**可維護性投資**。建立團隊規範、配置自動格式化、CI 守門,能讓每個開發者專注於邏輯而非格式糾紛,長期回報率極高。