问题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>
正常逻辑来想,.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,效果图如下
结果是,我发现了内层第二个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;
}
则会显示如下
简单来说,就是:nth-of-type(),用标签类型来判断,而不是dom的顺序了