前言
ul>li:nth-child(3)
找到li标签的父亲的第三个孩子,这个孩子也必须是li,选择器才能生效
ul>li:nth-of-type(3)
找到li标签同级的所有的li,并从中找到第三个li
注意:
:nth-child(3)和:nth-of-type(3)只适合简单的层级结构,不然会出问题。比如:ul>li tr>td
demo1 - 被误伤
css
.fu {
height: 100px;
padding: 30px 100px;
}
.zi1, .zi2 {
position: relative;
float: left;
width: 100px;
height: 100px;
}
.fu div:nth-child(1) {
background-color: pink;
}
.zi2 {
background-color: #ccc;
}
.grandson1 {
position: absolute;
left: 210px;
}
html
<div class="fu">
<div class="zi1">
<div class="grandson1">grandson1</div>
</div>
<div class="zi2">
<div class="grandson2">grandson2</div>
</div>
</div>
结果
demo1 - 正常
后代选择器 改成 父子选择器
css
.fu {
height: 100px;
padding: 30px 100px;
}
.zi1, .zi2 {
position: relative;
float: left;
width: 100px;
height: 100px;
}
/* .fu div:nth-child(1) { */
.fu>div:nth-child(1) {
background-color: pink;
}
.zi2 {
background-color: #ccc;
}
.grandson1 {
position: absolute;
left: 210px;
}
html
<div class="fu">
<div class="zi1">
<div class="grandson1">grandson1</div>
</div>
<div class="zi2">
<div class="grandson2">grandson2</div>
</div>
</div>
结果
demo2 - 正常
css
.fu {
margin: 100px;
}
.fu>div:nth-child(4) {
background: tan;
}
.fu>div:nth-of-type(3) {
background: pink;
}
html
<div class="fu">
<p>
son1---p1
</p>
<p>son2---p2</p>
<div>son3---div1</div>
<div>son4---div2</div>
<div>son5---div3</div>
</div>
结果:
demo2 - 不正常
css
.fu {
margin: 100px;
}
.fu>div:nth-child(4) {
background: tan;
}
.fu>div:nth-of-type(3) {
background: pink;
}
html
<div class="fu">
<p>
son1---p1
<p>grandson1---p1</p>
<p>grandson2---p2</p>
<div>grandson3---div1</div>
<div>grandson4---div2</div>
<div>grandson5---div3</div>
</p>
<p>son2---p2</p>
<div>son3---div1</div>
<div>son4---div2</div>
<div>son5---div3</div>
</div>
结果
总结
1 使用父子选择器
2 父子选择器中的父级使用类名,减少误伤的概率。
3 子级不要再有太多的子级了,不然就会出现demo2这种无法解释的情况
解释不了,就很烦
解释不了,就很烦!!!解释不了,就很烦!!!