* 通用選擇器E 類型選擇器.class 類選擇器#id ID 選擇器E F 後代選擇器E:link / :visited / :active / :hover 偽類E:first-line / :first-letter 偽元素E > F 子選擇器E + F 相鄰兄弟選擇器E[attr] E[attr="val"] E[attr~="val"] E[attr|="val"] 屬性選擇器E:first-child 結構偽類E:lang(c) 語言偽類E::before / ::after 偽元素(雙冒號語法 Level 3 規範):nth-child(n) :nth-last-child(n) :nth-of-type(n) :first-of-type :last-of-type :only-child :only-of-type :empty :root:enabled / :disabled / :checked / :indeterminate :valid / :invalid / :in-range / :out-of-range :required / :optional :read-only / :read-write :placeholder-shown :default:target:not(X) (單參數)E ~ F 通用兄弟選擇器E[attr^="val"] (開頭) E[attr$="val"] (結尾) E[attr*="val"] (包含):not(.a, .b, [hidden])div:has(> img)、label:has(+ input:checked)、**改變 CSS 單向流向的里程碑**:is(h1,h2,h3) > a、:where(.a, .b) .c (:where 優先級為 0)li:nth-child(2 of .active)element.querySelector(':scope > .child'))/* 四元組 (A, B, C, D) — 十進制比較,非進位制 */
內聯 style="" → (1,0,0,0) = 1000
ID 選擇器 #id → (0,1,0,0) = 100
類/屬性/偽類 .class → (0,0,1,0) = 10
標簽/偽元素 div ::before→ (0,0,0,1) = 1
通用 * / 組合器 > + ~ → (0,0,0,0) = 0
/* 實例 */
#nav .item a:hover → (0,1,2,1) = 121
div.content p → (0,0,0,2) = 2
:where(.a, #b) .c → (0,0,1,0) = 10 (:where 優先級歸零)
/* 表單驗證狀態 */
.field:has(input:invalid) .field__error { display: block; }
.field:has(input:valid) .field__success { display: block; }
/* 容器根據子元素狀態變化 */
.card:has(.badge--new) { border-color: #007bff; }
.card:has(img) { padding: 0; } /* 有圖片時移除內邊距 */
/* 導航當前項父級高亮 */
.nav__item:has(.nav__link[aria-current="page"]) { background: #f0f7ff; }
/* 重置類:極低優先級,易被覆蓋 */
:where(ul, ol) { list-style: none; padding: 0; margin: 0; }
/* 工具類:高優先級,強制生效 */
:is(.u-hidden, [hidden]) { display: none !important; }
/* 組件內部:限制作用域 */
.card :is(.title, .heading) { font-size: 1.25rem; }
/* 列表項 ≥ 5 時改為網格 */
.grid:has(> :nth-child(5)) { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
/* 精確 3 項時特殊佈局 */
.items:has(> :nth-child(3):last-child) { display: flex; justify-content: space-between; }
/* 必填標記自動生成 */
label:has(+ input[required])::after { content: " *"; color: #ef4444; }
/* 聚焦時顯示幫助文本 */
.field:focus-within .field__hint { opacity: 1; visibility: visible; }
/* 輸入時實時驗證反饋 */
input:user-invalid { border-color: #ef4444; }
input:user-valid { border-color: #22c55e; }
| 反模式 | 開銷 | 優化 |
|---|---|---|
.container div span a 深層後代 | 向上遍歷 DOM 樹,O(N×深度) | 直接類選擇器 .link |
* { } 通用選擇器作關鍵選擇符 | 匹配所有元素 | 避免作為關鍵選擇符(最右側) |
div > * + * + * 複雜組合器 | 瀏覽器匹配引擎回溯次數激增 | 拆分為語義類 |
屬性選擇器 [class*="col-"] | 字符串匹配慢於哈希查找 | 改用明確類名 |
:has() 濫用於高頻重繪容器 | 每次佈局觸發父鏈檢查 | 限制範圍、配合 contain:layout |
選擇器是 CSS 的「查詢語言」。掌握 Level 4 的邏輯能力,配合優先級科學管理,能讓樣式表從「堆砌代碼」進化為「可推理的設計系統」。