子元素自動獲得父元素特定屬性(如 color、font、line-height、text-align 等)的計算值,無需重複宣告。善用繼承,能大幅精簡樣式表。
#container li { font-family: Georgia, serif; }
#container p { font-family: Georgia, serif; }
#container h1 { font-family: Georgia, serif; }
#container { font-family: Georgia, serif; }
所有後代 li、p、h1 自動繼承,若個別需要調整,再局部覆蓋即可。
| 可繼承(常用) | 不可繼承(常用) |
|---|---|
| color | border |
| font / font-* | margin / padding |
| line-height | width / height |
| text-align / text-indent | position / top / left |
| list-style | background |
| visibility | display / flex / grid |
| cursor | overflow / z-index |
.reset-color { color: inherit; } /* 強制繼承父色 */
.no-inherit { color: initial; } /* 重置為瀏覽器預設 */
.explicit { color: unset; } /* 可繼承則繼承,否則初始值 */
:root {
--font-base: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--text-color: #1a1a1a;
}
body {
font-family: var(--font-base);
color: var(--text-color);
line-height: 1.6;
}
/* 元件層級僅覆蓋差異 */
.btn { font-weight: 600; }
.code { font-family: monospace; }
* { font-family: ... },破壞表單元素原生字體繼承行為。line-height 的無單位值繼承特性(1.5 會傳遞比例,而非像素值)。掌握繼承機制,是從「寫樣式」進階到「設計系統」的分水嶺。更多 CSS 架構技巧,請持續關注。