# nth-child nth-of-type区分

# first-child 和 first-of-type

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
		<style>
			*{
				margin:0;
				padding:0;
			}
			.k1,.k2{
				border:1px solid ;
			}
			.k1 section:first-child{
				color:red
			}
			.k2 section:first-of-type{
				color:blue
			}
		</style>
	</head>
	<body>
		<div class="k1">
			<section>第一个section</section>
			<div>
				<section>div里的一个section</section>
				<section>
					<div>xxxxxx</div>
					<section>999999</section>
				</section>
			</div>
			<div>
				<div>122222</div>
				<section>9999</section>
			</div>
		</div>
		<div class="k2">
			<section>第一个section</section>
			<div>
				<section>div里的一个section</section>
				<section>
					<div>xxxxxx</div>
					<section>999999</section>
				</section>
			</div>
			<div>
				<div>122222</div>
				<section>9999</section>
				<section>3333</section>
			</div>
		</div>
	</body>
</html>

第一个section
div里的一个section
xxxxxx
999999
122222
9999
第一个section
div里的一个section
xxxxxx
999999
122222
9999
3333

first-child父元素的第一个子元素是否符合条件,不符合就直接排除,first-of-type 找到选择的元素的父元素第一个符合要求的子元素;

  • .k1 section:first-child=>1.在类为k1的元素包裹下的元素 2.所有的section元素才有资格 3.section在当前兄弟元素是不是第一个,是选中,否则结束。
  • .k2 section:first-of-type=>1.在类为k2的元素包裹下的元素 2.所有的section元素才有资格 3.在当前兄弟元素中,第一个section即为选中的内容,不管位置是不是第一。

# :nth-child

如div:nth-child(n),要 同级 元素往下数,第n个符合就执行,不符合就不执行

div:nth-of-type(n),要 同级 元素且是同类型的往下数的第n个

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>压缩图片demo</title>
	<style>
		#parent div:nth-of-type(3){
				width:100px;
				height:100px;
				background:greenyellow;
				line-height:100px;
				text-align:center;
			}
			#parent div:nth-child(5){
				color:blue;
			}
			#parent div:nth-child(4){
				color:blue;
				font-weight: 700;
			}
			#parent div:nth-child(2){
				color:red;
				font-weight: 700;
			}
	</style>
</head>
<body>
	<div id="parent">
			<div>1</div>
			<div>2
				<div>2-1</div>
			</div>
			<p>3</p>
			<p>4</p>
			<div>5</div>
			<div>6</div>
			<div>7</div>
	</div>
</body>
<script>

</script>
</html>

1
2
2-1

3

4

5
6
7

总结

nth-child(n)/first-child/last-child 要选择元素的子元素往下数,第n个符合就执行,不符合就不执行(按位置来判断) nth-of-type(n)/first-of-type/last-of-type 要选择元素的子元素且是同类型的往下数的第n个 (按类型来判断)

最后更新: 1/27/2022, 8:43:28 AM