復合選擇器由多個簡單選擇器組合而成,透過結構關係、屬性特徵、狀態等條件,精準鎖定目標元素,減少對 HTML 結構添加 class 的依賴。
/* 僅選擇直接子元素 */
#nav > li { display: inline-block; }
.article > p:first-child { margin-top: 0; }
差異:div p(後代,含孫代)vs div > p(僅直接子代)。
/* 緊鄰在 h1 後的第一個 p */
h1 + p { margin-top: 0; font-size: 1.125rem; color: #666; }
常用於:標題後首段不縮進、表單標籤與輸入框間距、分隔線。
/* h1 之後所有同層 p */
h1 ~ p { color: #444; }
/* header 內所有 p */
header p { color: #fff; }
/* main 內所有 p */
main p { color: #333; }
⚠️ 效能最低,避免過度嵌套(如 .a .b .c .d)。
#wrap #header h2 span { font-size: 24px; }
#wrap #main h2 span { font-size: 14px; }
同一標籤在不同區塊呈現不同樣式,體現「上下文樣式」概念。
| 語法 | 匹配條件 | 範例 |
|---|---|---|
| [attr] | 擁有該屬性 | a[target] |
| [attr=val] | 屬性值完全等於 | input[type="email"] |
| [attr~=val] | 空格分隔值中包含 | img[alt~="logo"] |
| [attr|=val] | 連字號分隔值以 val 開頭 | [lang|="zh"] |
| [attr^=val] | 值以 val 開頭 | a[href^="https://"] |
| [attr$=val] | 值以 val 結尾 | a[href$=".pdf"] |
| [attr*=val] | 值包含 val 字串 | img[src*="avatar"] |
:first-child, :last-child, :nth-child(n), :nth-last-child(n)
:first-of-type, :last-of-type, :nth-of-type(n)
:only-child, :only-of-type, :empty
:hover, :focus, :focus-visible, :focus-within
:active, :visited, :link
:enabled, :disabled, :checked, :indeterminate
:valid, :invalid, :required, :optional
:in-range, :out-of-range
::before, ::after /* 生成內容,需 content 屬性 */
::first-line, ::first-letter
::selection, ::marker, ::placeholder
a:link { color: #0066cc; }
a:visited { color: #663399; }
a:hover { color: #e74c3c; text-decoration: underline; }
a:active { color: #c0392b; }
記憶口訣:LoVe HAte(Love → :link/:visited,Hate → :hover/:active)。
ID、class、標籤*、屬性選擇器、偽類作為關鍵選擇器.btn 優於 .header .nav .btn:where()、:is() 降低優先級(現代瀏覽器支援)精通選擇器後,建議學習 DIV 文字絕對置中技巧,解決經典佈局難題。