:nth-child() 选择器,问题

问题1,
可能存在的顺序问题

<!DOCTYPE html>
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		.out .other {
			background-color: red;
		}



		.out .inner:nth-child(2) {
			background-color: green;
		}

		.out .inner:first-child {
			background-color: blue;
		}

		.out .inner:nth-child(3) {
			background-color: yellow;
		}
	</style>
	<title>nth-child</title>
</head>

<body>

	<div class="out">
		<!-- <p> -->
		<div class="other">
			我是随便的一个div
		</div>
		<div class="inner">
			我是内层第一个div
		</div>
		<div class="inner">
			我是内层第二个div
		</div>
		<!-- </p> -->
	</div>

	<script src="./js/jquery-3.4.1.js" defer></script>
	<script type="text/javascript"></script>
</body>

</html>

图1
正常逻辑来想,.out里面的第一个inner在样式中设置得.out .inner:first-child 是background-color:blue,单实际情况,取的是.out .inner:nth-child(2)中的样式

给我的感觉更像是用的nth-of-type方法在处理

简单来说,我是这么理解的,因为.inner,上,有一个.other的div,那么在用nth-child做筛选的时候,先判断了,标签的名称(目前案例中都是div),在从.out中进行遍历div,所以,我们以为的第一个.inner,实际中.out的第二个div,则.out .inner:nth-child(2)生效;又因为first-child的class是other不是inner,不匹配,所以.out .inner:first-child,不生效

如果换成.out .other:first-child {background-color: blue;},则样式会生效,显示在.other上

问题2:
可能存在的嵌套问题

<!DOCTYPE html>
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		.out .other {
			background-color: red;
		}

		.out .inner:nth-child(2) {
			background-color: green;
		}

		.out .inner:first-child {
			background-color: blue;
		}

		.out .inner:nth-child(3) {
			background-color: yellow;
		}
	</style>
	<title>nth-child</title>
</head>

<body>

	<div class="out">
		<p>
			<div class="other">
				我是随便的一个div
			</div>
			<div class="inner">
				我是内层第一个div
			</div>
			<div class="inner">
				我是内层第二个div
			</div>
		</p>
	</div>

	<script src="./js/jquery-3.4.1.js" defer></script>
	<script type="text/javascript"></script>
</body>

</html>

这段代码与第一段,代码的区别就是,在内层3个div外,套了一层p,效果图如下
图2

结果是,我发现了内层第二个div,采用的样式是.out .inner:nth-child(3) 中的样式,我是这么理解的,遍历取样式的时候,外层的p标签算了一层,所以index(序号)就+1了

如果将css样式换成

		.out .other {
			background-color: red;
		}

		.out .inner:nth-of-type(2) {
			background-color: green;
		}

		.out .inner:first-child {
			background-color: blue;
		}

		.out .inner:nth-of-type(3) {
			background-color: yellow;
		}

则会显示如下
图3
简单来说,就是:nth-of-type(),用标签类型来判断,而不是dom的顺序了

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值