HTML 看似簡單,但細節決定成敗。以下整理實務開發中最高頻的 5 大錯誤,涵蓋渲染異常、維護地獄、效能陷阱、無障礙缺失與語意錯誤,附帶檢測工具與修正範例。
開發者假設瀏覽器預設白背景,未在 body 或 html 設定 background-color。使用者若自訂系統深色模式或瀏覽器預設背景非白,頁面將出現「透明區塊」、文字難讀、邊界模糊。
/* CSS Reset 必備 */
html { background-color: #fff; }
body { background-color: #fff; color: #1a1a1a; }
即使設計稿為深色背景,也要明確宣告:
body { background-color: #1a1a2e; color: #eee; }
<div align="center"> 置中<table>
<tr>
<td><div align="center">標題</div></td>
<td><div align="center"><img src="icon.png"></div></td>
</tr>
</table>
align 屬性已在 HTML5 棄用<div>,增加 DOM 深度與維護成本text-align、vertical-align<div> 造成結構混亂<!-- 表格儲存格置中 -->
<td style="text-align: center; vertical-align: middle;">內容</td>
<!-- 區塊置中(現代 Flexbox) -->
<div style="display: flex; justify-content: center; align-items: center;">內容</div>
<!-- 文字置中 -->
<p style="text-align: center;">文字</p>
<center><p><font><font><font color="#CCC"><font color="#FFA76C" style="font-size:14px;font-family:隸書">標題</font></font></font></font></p></center>
<font> 疊加,最後只生效最內層<center>、<font> 皆為 HTML5 棄用標籤<style>
.heading {
font: 14px/1.5 '標楷體', cursive;
color: #FFA76C;
text-align: center;
}
</style>
<h2 class="heading">標題</h2>
<table> 內,巢狀 4-5 層<header>, <main>, <aside>, <footer> + CSS Grid/Flexbox<iframe> 或非同步載入 <div id="counter"> + JS 插入<div id="counter-container" aria-label="訪客計數">載入中…</div>
<script>
fetch('/api/counter').then(r => r.text()).then(html => {
document.getElementById('counter-container').innerHTML = html;
}).catch(() => {
document.getElementById('counter-container').textContent = '無法載入';
});
團隊協作時,空白數不一(2/4/8 空格)導致版本控制噪音、代碼對齊崩壞、編輯器縮排邏輯混淆。
# .editorconfig
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{html,css,js,ts,vue,jsx,tsx}]
indent_size = 2
prettier --check 阻擋不合格提交| # | 錯誤 | 檢測方式 | 修正 |
|---|---|---|---|
| 6 | 缺少 <!DOCTYPE html> | 啟用 Quirks Mode | 首行強制宣告 |
| 7 | <img> 缺 alt | Lighthouse / axe-core | 裝飾性圖片 alt="",資訊性圖片描述內容 |
| 8 | 表單輸入框無 <label> 關聯 | 點擊文字無法聚焦輸入框 | <label for="id"> + <input id="id"> |
| 9 | 標題層級跳躍 | h1 → h3 無 h2 | 嚴格 h1-h6 階層 |
| 10 | 內聯樣式/事件屬性 | style="" onclick="" | 外部 CSS/JS、事件委派 |
| 11 | 重複 ID | W3C Validator | 唯一 ID、BEM 命名 |
| 12 | 不閉合標籤 | 瀏覽器自動補全導致結構偏差 | 所有容器標籤正確閉合 |
| 13 | 語意標籤濫用 | <section> 當 <div> 用 | 理解語意:section=主題區塊、article=獨立內容 |
| 14 | Meta viewport 缺失 | 行動裝置縮放異常 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 15 | Script 阻塞渲染 | <script src=""> 在 head | defer 或放在 </body> 前 |
# 專案整合
npm install -D htmlhint @html-eslint/parser @html-eslint/eslint-plugin prettier
# package.json scripts
"lint:html": "htmlhint \"**/*.html\"",
"format": "prettier --write \"**/*.{html,css,js,ts,json,md}\"",
"check": "npm run lint:html && prettier --check ."
HTML 品質直接影響 CSS/JS 維護成本、SEO 排名、無障礙合規與使用者體驗。建立團隊規範、導入自動化檢測、定期重構技術債,才能避免「能跑就好」的技術破產。