基石:字符編碼宣告 —— 亂碼的根治
<meta charset="utf-8">
<!-- HTML5 簡潔寫法,必須置于 <head> 首位,早于任何可見字符 -->
- UTF-8 涵蓋全球所有字符,含Emoji,是Web唯一標準編碼
- 舊專案遷移:資料庫/文件/HTTP Header/HTML Meta 四位一體轉碼
- HTTP Header
Content-Type: text/html; charset=utf-8 優先級高于 Meta 標籤
字體加載策略:系統字體棧 + Web Font 漸進增強
現代系統字體棧 (零請求、零閃爍、原生質感)
font-family:
system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC',
'Helvetica Neue', Arial, sans-serif;
品牌字體 Web Font 最佳實踐
- 格式: 僅提供
.woff2 (現代瀏覽器覆蓋率>95%) + 可選 .woff 兼容舊版
- 子集化:
pyftsubset / fonttools 提取常用字符集 (中文常用3500字 + 標點 + 英數),體積從MB級降至50-150KB
- 預載入:
<link rel="preload" as="font" href="font.woff2" crossorigin>
- 顯示策略:
font-display: swap; 確保文字即時可見 (FOUT優於FOIT)
- Variable Font: 單文件包含全字重/寬度/斜度,體積減60%+,動態變化流暢
CSS排版核心屬性系統化
| 屬性類別 | 關鍵屬性 | 現代最佳實踐 |
| 字體 | font-family, font-size, font-weight, font-style, font-stretch, font-variant | 使用 font: var(--font-body) / var(--line-height-body) var(--font-family); 設計令牌統一管理 |
| 行高/字距 | line-height, letter-spacing, word-spacing | 無單位行高 1.6 繼承安全;中文 letter-spacing: 0.02em 微調 |
| 對齊/換行 | text-align, text-justify, white-space, word-break, overflow-wrap, hyphens | 中文 word-break: break-word; overflow-wrap: break-word; 禁止 word-break: break-all |
| 裝飾/變換 | text-decoration, text-transform, text-shadow, font-variant-ligatures | 連字 font-variant-ligatures: common-ligatures; 提升專業感 |
| 響應式 | clamp(), viewport units, container queries | font-size: clamp(1rem, 0.9rem + 0.5vw, 1.25rem); 流體排版無斷點 |
超鏈接樣式系統:可訪問、可預期、有層級
:root {
--color-link: #0066cc;
--color-link-hover: #004499;
--color-link-visited: #663399;
--color-link-focus: #ffbf00;
--color-link-active: #003366;
}
a { color: var(--color-link); text-decoration: underline; text-underline-offset: 2px; text-decoration-thickness: 1px; }
a:hover { color: var(--color-link-hover); text-decoration-thickness: 2px; }
a:visited { color: var(--color-link-visited); }
a:focus-visible { outline: 2px solid var(--color-link-focus); outline-offset: 2px; border-radius: 2px; }
a:active { color: var(--color-link-active); }
/* 非導航區塊內文鏈接下劃線,導航/按鈕狀鏈接無下劃線 */
.nav a, .btn-link { text-decoration: none; }
外部樣式表模組化架構
/* tokens.css 設計令牌 */
:root { --font-size-base: 1rem; --line-height-base: 1.6; --font-family-base: ...; }
/* base.css 重置與基礎排版 */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { font-size: 100%; -webkit-text-size-adjust: 100%; }
body { font: var(--font-size-base)/var(--line-height-base) var(--font-family-base); color: #1a1a1a; }
/* components/links.css, components/buttons.css, components/forms.css ... */
/* main.css 入口 */
@import 'tokens.css';
@import 'base.css';
@import 'components/links.css';
/* ... */
/* HTML引入 */
<link rel="stylesheet" href="/assets/css/main.css">
常見排版陷阱避坑
- ❌
font-size: 12px 固定像素 → 用戶無法縮放,違反無障礙
- ❌
line-height: 20px 帶單位 → 繼承失效,父子元素行高錯亂
- ❌ 中文強制
font-family: "Microsoft YaHei" → 跨平台回退失控
- ❌
text-align: justify 中文兩端對齊 → 河流效應嚴重,閱讀極差
- ✅ 相對單位 + 設計令牌 + 系統字體棧 + 國際化API = 穩健、可維護、無障礙的排版系統