CSS 选择器用于选择 HTML 元素并应用样式。以下是常见的 CSS 选择器及其使用方法:
### 1. 基本选择器
- **元素选择器**:
选择所有指定类型的元素。
```css
p {
color: blue; /* 所有 <p> 元素变为蓝色 */
}
```
- **类选择器**:
选择具有指定类的元素,前面加点号 (`.`)。
```css
.container {
margin: 20px; /* 所有 class="container" 的元素 */
}
```
- **ID 选择器**:
选择具有指定 ID 的元素,前面加井号 (`#`)。
```css
#header {
background-color: gray; /* ID 为 header 的元素 */
}
```
### 2. 组合选择器
- **后代选择器**:
选择某个元素内的所有指定后代元素。
```css
div p {
font-size: 16px; /* 所有 <div> 内的 <p> 元素 */
}
```
- **子选择器**:
选择某个元素的直接子元素。
```css
ul > li {
list-style-type: square; /* 仅选择 <ul> 的直接 <li> 子元素 */
}
```
- **相邻兄弟选择器**:
选择紧接在另一个元素后的兄弟元素。
```css
h1 + p {
margin-top: 0; /* 选择紧接在 <h1> 后的 <p> 元素 */
}
```
- **通用兄弟选择器**:
选择某个元素后面的所有兄弟元素。
```css
h1 ~ p {
color: red; /* 所有在 <h1> 后的 <p> 元素 */
}
```
### 3. 属性选择器
- **基本属性选择器**:
选择具有特定属性的元素。
```css
a[target] {
color: green; /* 所有带有 target 属性的 <a> 元素 */
}
```
- **值选择器**:
选择具有特定属性值的元素。
```css
input[type="text"] {
border: 1px solid black; /* 所有 type 为 text 的 <input> 元素 */
}
```
### 4. 伪类选择器
- **链接伪类**:
选择链接的不同状态。
```css
a:link {
color: blue; /* 普通链接 */
}
a:visited {
color: purple; /* 已访问链接 */
}
a:hover {
color: red; /* 鼠标悬停链接 */
}
a:active {
color: orange; /* 点击链接时 */
}
```
- **结构伪类**:
选择特定位置的元素。
```css
p:first-child {
font-weight: bold; /* 第一个子元素的 <p> */
}
li:nth-child(2) {
color: orange; /* 第二个 <li> 元素 */
}
```
### 5. 伪元素选择器
- **内容插入**:
选择元素的一部分,通常用于添加样式。
```css
p::first-line {
font-weight: bold; /* <p> 的第一行 */
}
p::before {
content: "Note: "; /* 在每个 <p> 前插入内容 */
font-weight: bold;
}
```
### 小结
CSS 选择器提供了强大的方式来选择和样式化 HTML 元素。通过合理使用这些选择器,可以高效地控制网页的外观和布局。