🌟 一、基础选择器(Basic Selectors)

1. 元素选择器

选择某种标签的所有元素。

1
2
3
4
5
6
7
8
9
p {
color: blue;
}




<p>我是段落文字</p>
<div>我不会变蓝</div>

2. 类选择器(Class Selector)

使用 . 开头,选择 class 属性的元素。

1
2
3
4
5
6
7
.box {
border: 1px solid black;
}



<div class="box">我是一个盒子</div>

3. ID 选择器

使用 # 开头,选中具有特定 id 的元素(一个页面中只能有一个相同 ID)。

1
2
3
4
5
6
7
8
9
#main {
background-color: yellow;
}





<div id="main">我是主区域</div>

🌟 二、组合选择器(Group, Descendant, Child, etc)

4. 组合选择器

同时选中多个选择器。

1
2
3
h1, h2, p {
font-family: Arial;
}

5. 后代选择器(Descendant Selector)

空格表示选择某元素内的子孙元素。

1
2
3
4
5
6
7
8
9
10
div p {
color: red;
}




<div>
<p>我会变红</p>
</div>

6. 子选择器(Child Selector)

使用 >,只选中直接子元素。

1
2
3
4
5
6
7
8
9
ul > li {
list-style: square;
}



<ul>
<li>✔ 直接子元素</li>
</ul>

7. 相邻兄弟选择器(Adjacent Sibling +

选中紧挨着的下一个兄弟元素。

1
2
3
4
5
6
7
8
h1 + p {
color: green;
}



<h1>标题</h1>
<p>紧跟其后的段落变绿</p>

8. 通用兄弟选择器(General Sibling ~

选中同级别中,后续所有匹配的兄弟元素

1
2
3
h1 ~ p {
color: orange;
}

🌟 三、属性选择器(Attribute Selectors)

1
2
3
4
5
6
7
8
9
input[type="text"] {
border: 1px solid gray;
}




<input type="text" />
<input type="password" />

🌟 四、伪类选择器(Pseudo-classes)

9. :hover 鼠标悬停

1
2
3
a:hover {
color: red;
}

10. :first-child 第一个子元素

1
2
3
li:first-child {
font-weight: bold;
}

11. :nth-child(n) 第 n 个子元素

1
2
3
li:nth-child(2) {
color: blue;
}

🌟 五、伪元素选择器(Pseudo-elements)

12. ::before / ::after

用于在元素前后插入内容(通常配合 content 使用)

1
2
3
4
5
6
7
8
p::before {
content: "👉 ";
}
html


复制编辑
<p>这是段落</p>

✅ 小结表格(常用)

选择器 示例 作用
元素选择器 p 选中所有 <p> 元素
类选择器 .class 选中 class 为 class 的元素
ID 选择器 #id 选中 id 为 id 的元素
后代选择器 div p 选中 div 中所有的 p
子选择器 div > p 选中 div 中直接子元素 p
相邻兄弟选择器 h1 + p 选中紧挨 h1 的 p
通用兄弟选择器 h1 ~ p 选中 h1 后所有兄弟 p
属性选择器 input[type="text"] 选中特定属性值的元素
伪类选择器 a:hover 鼠标悬停时生效
伪元素选择器 p::before 在元素前插入内容