子元素**自動獲得**父元素特定屬性的**計算值**。繼承發生在**計算值階段**,而非指定值。只有部分屬性預設可繼承。
| 可繼承 (常用) | 不可繼承 (常用) |
|---|---|
| color | border / border-* |
| font / font-* | margin / padding |
| line-height | width / height / max-* / min-* |
| text-align / text-indent / text-transform | position / top / right / bottom / left |
| letter-spacing / word-spacing | display / flex-* / grid-* |
| list-style / list-style-* | background / background-* |
| visibility | overflow / clip / z-index |
| cursor | float / clear |
| quotes | transform / opacity / filter |
完整清單請參考 MDN CSS properties reference → Inherited: yes/no。
body {
font-family: system-ui, sans-serif;
color: #1a1a1a;
line-height: 1.6;
}
/* 所有後代自動擁有以上字體、顏色、行高 */
h1 { font-size: 2rem; font-weight: 700; } /* 僅覆蓋大小/粗細 */
blockquote { font-style: italic; color: #555; } /* 覆蓋顏色、風格 */
| 關鍵字 | 行為 | 適用屬性 | 範例 |
|---|---|---|---|
inherit | **強制繼承**父元素計算值 | 所有屬性 | a { color: inherit; } 連結跟隨父色 |
initial | 重置為**瀏覽器預設值** (CSS 規範初始值) | 所有屬性 | .reset { all: initial; } 完全重置 |
unset | 可繼承屬性→inherit,不可繼承→initial | 所有屬性 | .btn { all: unset; } 清除 UA 樣式 |
/* 只有 .article 內的 ul > li > a 變綠 */
.article ul li a { color: green; }
/* 等價簡寫 (利用繼承) */
.article a { color: green; } /* 所有後代 a 皆綠 */
/* 只針對第三層列表項目 */
.article > ul > li > ul > li > ul > li { color: green; }
.article ul ul ul li { color: green; } /* 更簡潔 */
/* CSS */
ul li ul li { color: green; }
/* HTML */
- 項目 1
- 項目 1-1
- 項目 1-2
- 項目 1-2-1
- 項目 2
答案:3 行 (項目 1-1、1-2、1-2-1)。
解析:選擇器 ul li ul li 匹配「ul 的後代 li,且該 li 是 ul 的後代」。項目 1 是第一層 li,不匹配;項目 1-1、1-2 是第二層 li (祖先有 ul→li→ul),匹配;項目 1-2-1 是第三層 li,祖先鏈包含兩組 ul→li,同樣匹配;項目 2 是第一層,不匹配。
a 設定了具體色彩,**阻斷繼承**。需額外 a { color: inherit; }。input, textarea, select, button **不繼承 font-family/size**。現代 Reset 必加:input, button, textarea, select { font: inherit; }。:root 或 html 定義 Design Tokens (CSS 變數) 作為字體、色彩、間距單一真實來源。*, *::before, *::after { box-sizing: border-box; } + html { font-size: 100%; } + body { font-family: inherit; }。all: initial/unset 封裝第三方元件或重置區塊。繼承是 CSS 區別於傳統程式語言的獨特機制。善用繼承減少重複、建立一致基線、配合關鍵字精準控制,是寫出可維護 CSS 的關鍵功力。更多 CSS 架構實戰,請關注本站設計系統系列。