🎯 CSS :is()
& :where()
實戰指南:簡化選擇器,提升可維護性
你是否在項目中寫過一大串重復的選擇器?比如:
h1, h2, h3, h4, h5, h6 { margin-bottom: 1rem; }
這樣的代碼既冗長又難維護。
現在 CSS 提供了:is()
和:where()
選擇器,讓你可以寫得更短、更優雅,還能更好地控制優先級。
🧠 什么是 :is()
和 :where()
?
它們都是 選擇器列表函數,允許你在一個規則中傳入多個候選選擇器:
:is()
:匹配多個選擇器,計算 正常的優先級:where()
:匹配多個選擇器,但 權重始終為 0
? 基礎示例
/* 用 :is() 簡化 */
:is(h1, h2, h3, h4, h5, h6) {margin-bottom: 1rem;
}
效果等同于:
h1, h2, h3, h4, h5, h6 {margin-bottom: 1rem;
}
🧪 實戰一:按鈕多狀態寫法
.button:is(:hover, :focus, :active) {background: #4f46e5;color: white;
}
📌 優勢:不再寫 .button:hover, .button:focus, .button:active
,簡潔很多。
🧪 實戰二:用 :where()
降低選擇器優先級
/* 全局 reset 樣式 */
:where(h1, h2, h3, p) {margin: 0;padding: 0;
}
📌 因為 :where()
權重為 0,后續樣式可以輕松覆蓋,不會“打架”。
🌟 高級技巧
-
組合選擇器
.card :is(h2, h3) {color: #111; }
? 匹配
.card
內的所有h2
和h3
。 -
與偽類結合
nav :is(a:hover, a:focus) {text-decoration: underline; }
-
重置 + 覆蓋最佳實踐
- 用
:where()
寫 Reset(低優先級) - 用
:is()
寫組件邏輯(正常優先級)
- 用
🌐 瀏覽器支持(2025)
瀏覽器 | 支持情況 |
---|---|
Chrome 88+ | ? |
Safari 15+ | ? |
Firefox 78+ | ? |
Edge 88+ | ? |
📌 幾乎已完全普及,可以放心用在生產環境。
?? 注意事項
-
:is()
的權重 = 里面最具體選擇器的權重div:is(.highlight, #id) { ... }
權重會按
#id
來算。 -
:where()
永遠是 0 權重,適合寫 Reset 或全局初始化。 -
不要濫用,否則可讀性可能下降。
? 一句話總結
:is()
和:where()
是現代 CSS 的“選擇器助手”,讓你的樣式更簡潔、更可維護,合理利用權重差異,還能輕松寫出優雅的架構。