CSS選擇器用于選擇HTML元素并為其應用樣式。以下是CSS中最常用的選擇器類型:
基本選擇器
1.元素選擇器?- 通過HTML標簽名選擇元素
p { color: blue; }
2.類選擇器?- 通過class屬性選擇元素(以.
開頭)
.warning { color: red; }
3.ID選擇器?- 通過id屬性選擇元素(以#
開頭)
#header { background: gray; }
4.通用選擇器 - 選擇所有元素(*)
* { margin: 0; padding: 0; }
組合選擇器
5.后代選擇器?- 選擇某個元素內的所有特定后代(空格分隔)
div p { font-size: 14px; }
6.子元素選擇器?- 選擇直接子元素(>
分隔)
ul > li { list-style: none; }
7.相鄰兄弟選擇器 - 選擇緊接在另一個元素后的元素(+分隔)
h1 + p { margin-top: 0; }
8.通用兄弟選擇器?- 選擇所有在指定元素之后的同級元素(~
分隔)
h2 ~ p { color: green; }
屬性選擇器
9.屬性存在選擇器?- 選擇具有特定屬性的元素
[disabled] { opacity: 0.5; }
10.屬性值選擇器?- 選擇屬性等于特定值的元素
[type="text"] { border: 1px solid #ccc; }
11.屬性值包含選擇器?- 選擇屬性值包含特定字符串的元素
[class*="btn"] { padding: 5px 10px; }
12.屬性值開頭選擇器?- 選擇屬性值以特定字符串開頭的元素
[href^="https"] { color: green; }
13.屬性值結尾選擇器?- 選擇屬性值以特定字符串結尾的元素
[src$=".png"] { border: 1px solid #eee; }
偽類選擇器
14.動態偽類
a:link { color: blue; } /* 未訪問鏈接 */
a:visited { color: purple; } /* 已訪問鏈接 */
a:hover { text-decoration: underline; } /* 鼠標懸停 */
a:active { color: red; } /* 激活/點擊時 */
15.結構偽類
li:first-child { font-weight: bold; } /* 第一個子元素 */
li:last-child { border-bottom: none; } /* 最后一個子元素 */
li:nth-child(2n) { background: #f5f5f5; } /* 偶數子元素 */
16.表單偽類
input:focus { outline: 2px solid blue; }
input:disabled { background: #eee; }
input:checked + label { font-weight: bold; }
偽元素選擇器
17.偽元素
p::first-line { font-weight: bold; } /* 第一行 */
p::first-letter { font-size: 2em; } /* 首字母 */
::before { content: "→"; } /* 在元素前插入內容 */
::after { content: "!"; } /* 在元素后插入內容 */
選擇器組合
18.多重選擇器?- 同時選擇多個元素(逗號分隔)
h1, h2, h3 { font-family: sans-serif; }
19.復合選擇器?- 組合不同類型的選擇器
button.primary { background: blue; } /* 類為primary的button元素 */