font 縮寫語法結構
font: [font-style] [font-variant] [font-weight] [font-size[/line-height]] [font-family];
/* ⚠️ 必填:font-size 和 font-family,其餘可省略 (套用預設值) */
/* ⚠️ 順序固定,不可亂序 */
/* ⚠️ line-height 必須緊跟 font-size,用斜線分隔 */
完整範例拆解
font: italic small-caps bold 1rem/1.5 "Noto Sans TC", sans-serif;
/* style variant weight size/line-h family */
各子屬性可用值
| 子屬性 | 可用值 | 預設值 |
font-style | normal | italic | oblique | normal |
font-variant | normal | small-caps | normal |
font-weight | normal | bold | bolder | lighter | 100–900 | normal (400) |
font-size | <length> | <percentage> | xx-small ~ xx-large | medium (~16px) |
line-height | normal | <number> | <length> | <percentage> | normal (~1.2) |
font-family | <family-name> | <generic-family> | 瀏覽器預設 |
常見寫法變體
| 寫法 | 展開結果 | 適用場景 |
font: 1rem sans-serif; | size=1rem, family=sans-serif, 其他預設 | 最簡潔,重置字體 |
font: bold 1.2rem/1.4 "Font", serif; | weight=bold, size=1.2rem, lh=1.4, family="Font", serif | 標題樣式 |
font: italic 0.875rem monospace; | style=italic, size=0.875rem, family=monospace | 代碼區塊 |
font: small-caps 1rem/1.6 Georgia, serif; | variant=small-caps, size=1rem, lh=1.6, family=Georgia | 文章首段裝飾 |
font: 700 1.5rem/1.2 system-ui; | weight=700, size=1.5rem, lh=1.2, family=system-ui | 現代系統字體 |
系統字體關鍵字 (不可拆分)
font: caption; /* 系統標題字體 */
font: icon; /* 系統圖示字體 */
font: menu; /* 系統選單字體 */
font: message-box; /* 系統對話框字體 */
font: small-caption; /* 系統小標題字體 */
font: status-bar; /* 系統狀態欄字體 */
/* 這些關鍵字會自動包含完整字體設定,不可與其他值混用 */
font 縮寫的重置陷阱 (最重要!)
/* 場景:父元素設定了 line-height: 1.8 */
.parent { line-height: 1.8; }
/* 子元素使用 font 縮寫,未指定 line-height */
.child { font: 1rem "Noto Sans", sans-serif; }
/* 結果:child 的 line-height 被重置為 normal (~1.2),而非繼承 1.8! */
/* 正確做法:明確指定 line-height */
.child { font: 1rem/1.8 "Noto Sans", sans-serif; }
/* 或分開聲明 */
.child { font-size: 1rem; font-family: "Noto Sans", sans-serif; }
預設值重置完整對照
font: 1rem sans-serif;
/* 等同於 */
font-style: normal;
font-variant: normal;
font-weight: normal;
font-size: 1rem;
line-height: normal; /* ⚠️ 不是 inherit! */
font-family: sans-serif;
現代最佳實踐建議
方案 A:分開聲明 (推薦團隊協作、可讀性優先)
.text-body {
font-family: "Noto Sans TC", system-ui, sans-serif;
font-size: 1rem;
line-height: 1.6;
font-weight: 400;
font-style: normal;
}
/* 修改單一屬性極其清晰 */
.text-body--large { font-size: 1.25rem; }
.text-body--bold { font-weight: 700; }
方案 B:CSS 變數 + 縮寫 (推薦設計系統)
:root {
--font-family-base: "Noto Sans TC", system-ui, sans-serif;
--font-size-base: 1rem;
--line-height-base: 1.6;
--font-weight-base: 400;
}
.text-body {
font: var(--font-weight-base) var(--font-size-base)/var(--line-height-base) var(--font-family-base);
}
/* 修改變數即可全域生效 */
@media (min-width: 768px) {
:root { --font-size-base: 1.125rem; }
}
方案 C:受控縮寫 (僅在受控元件內使用)
.btn {
/* 元件內部完全控制,無繼承副作用 */
font: 600 0.875rem/1.5 var(--font-family-base);
}
除錯技巧
- DevTools Computed 面板查看最終展開值
- 搜尋
font: 定位所有縮寫點
- Stylelint 規則
font-family-no-missing-generic-family-keyword 確保有通用字體回退
- 使用
font-size: 1rem 而非 16px,支援用戶縮放偏好