掌握選擇器分組與繼承機制,能大幅減少重複代碼,並精準控制樣式傳遞。
/* 所有標題統一顏色 */
h1, h2, h3, h4, h5, h6 {
color: #2c3e50;
font-weight: 600;
line-height: 1.3;
}
/* 表單元素統一字體 */
input, select, textarea, button {
font: inherit;
color: inherit;
}
可繼承屬性(常見):
color, font-*, line-height, text-align, text-indent, text-transform, letter-spacing, word-spacing, white-space, list-style, cursor, visibility, quotes 等。
不可繼承屬性(常見):
margin, padding, border, width, height, display, position, float, background, overflow, z-index, flex/grid 相關屬性等。
body 規則;表格元素 (table, td, th) 在 IE6-7 中不繼承字體屬性。/* 基礎規則 */
body { font-family: Verdana, sans-serif; }
/* 針對不支援繼承的舊瀏覽器,重複宣告 */
p, td, ul, ol, li, dl, dt, dd {
font-family: Verdana, sans-serif;
}
現代專案完全不需要,保留認知即可。
body { font-family: Verdana, sans-serif; }
p { font-family: Georgia, serif; } /* 擺脫 body 繼承,使用自己的字體 */
font-family: inherit 明確繼承(預設行為),或 initial 重置為初始值。| 關鍵字 | 行為 | 適用屬性 |
|---|---|---|
inherit | 強制繼承父元素計算值 | 所有屬性 |
initial | 重置為 CSS 規範定義的初始值 | 所有屬性 |
unset | 可繼承屬性→inherit,不可繼承→initial | 所有屬性 |
revert | 重置為使用者代理程式預設值(瀏覽器預設) | 所有屬性 |
revert-layer | 重置為上一個 Cascade Layer 的值 | 所有屬性 (CSS Cascade Layers) |
body 設定基礎 font-family, line-height, color,讓所有子元素自然繼承。.card { font-size: 0.9rem; color: #333; }),內部元素繼承。.text-center { text-align: center; } 直接覆蓋繼承。inherit:只在跨越隔離邊界(如 Shadow DOM、iframe、all: initial 重置後)需要時使用。理解繼承機制,能寫出更少代碼、更一致、更易維護的 CSS。