写一段结构伪类选择器的教学代码
时间: 2023-12-01 11:53:45 浏览: 26
好的,以下是一个简单的结构伪类选择器的教学代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>结构伪类选择器</title>
<style>
/* 选择第一个 <p> 元素 */
p:first-of-type {
background-color: yellow;
}
/* 选择最后一个 <p> 元素 */
p:last-of-type {
background-color: blue;
}
/* 选择第二个 <p> 元素 */
p:nth-of-type(2) {
background-color: green;
}
/* 选择每个偶数 <p> 元素 */
p:nth-of-type(even) {
background-color: pink;
}
/* 选择每个奇数 <p> 元素 */
p:nth-of-type(odd) {
background-color: orange;
}
</style>
</head>
<body>
<p>第一个段落。</p>
<p>第二个段落。</p>
<p>第三个段落。</p>
<p>第四个段落。</p>
<p>第五个段落。</p>
</body>
</html>
```
在上面的代码中,我们使用了结构伪类选择器来选择不同类型的 `<p>` 元素,并为它们设置不同的背景颜色。其中:
- `p:first-of-type` 选择第一个 `<p>` 元素,并将其背景颜色设置为黄色。
- `p:last-of-type` 选择最后一个 `<p>` 元素,并将其背景颜色设置为蓝色。
- `p:nth-of-type(2)` 选择第二个 `<p>` 元素,并将其背景颜色设置为绿色。
- `p:nth-of-type(even)` 选择每个偶数 `<p>` 元素,并将其背景颜色设置为粉色。
- `p:nth-of-type(odd)` 选择每个奇数 `<p>` 元素,并将其背景颜色设置为橙色。
你可以将上述代码复制到一个 HTML 文件中并在浏览器中打开,以查看不同的结构伪类选择器是如何运作的。