CSS中的:first-of-type和:last-of-type


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2020/03/17/CSS%E4%B8%AD%E7%9A%84-first-of-type%E5%92%8C-last-of-type/

摘要

本文主要讲述了:

  1. :first-of-type
  2. :last-of-type

正文

:first-of-type

用于设置:顺序第一个相同类型的子元素的样式

示例:将id=aid=b的背景颜色设为红色

  • id=a是顺序第1<p>
  • id=b是顺序第1<div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="foo">
<p id="a">p</p>
<p>p</p>
<div id="b">div</div>
<div>div</div>
</div>
<style>
#foo :first-of-type {
background-color: #f00;
}
</style>
</body>
</html>

:last-of-type

用于设置:逆序第一个相同类型的子元素的样式

示例:将id=aid=b的背景颜色设为红色

  • id=a是逆序第1<p>
  • id=b是逆序第1<div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="foo">
<div>div</div>
<div id="b">div</div>
<p>p</p>
<p id="a">p</p>
</div>
<style>
#foo :last-of-type {
background-color: #f00;
}
</style>
</body>
</html>

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2020/03/17/CSS%E4%B8%AD%E7%9A%84-first-of-type%E5%92%8C-last-of-type/


本文对你有帮助?请支持我


支付宝
微信