最近在做练习的时候发现,使用伪类选择器nth-of-type、nth-child时无法选到想要的元素,研究了一下发现是对这类伪类选择器的理解有点问题,下面先直接看代码
html代码
<style type="text/css">
div{
width: 50px;
height: 50px;
background-color: aqua;
margin: 20px auto;
}
</style>
<body>
<div class="demo">
<div class="a">
aa
<span class="c">c</span>
</div>
<div class="b">b1</div>
<div class="b">b2</div>
<div class="c">cc</div>
</div>
</body>
一开始页面是这样
现在我想选中 b1 这个盒子,给它加边框,但下面这种做法无效
然后我把它改成 nth-child(1) 、first-of-type 、 first-child 也都同样无效
但是给 .a:nth-of-type(1) 却能选中 aa c 这个盒子
然后查了些资料才发现是我对这些伪类选择器的理解有问题,比如 .class:nth-of-type(i) 我理解的是选择类名为class的第i个元素,这是有差误的。
.class:nth-of-type(i) 的真正意义是:
- 要选中的元素的类名是class
- 这个元素是它的父元素下同一个标签名的元素中的第 i 个
因为上面4个盒子都是div,所以 b1 盒子其实是它的父元素下同一个标签名的元素中的第2个,要把 i 改为 2 才行。
当 b1 盒子的容器不是div时,.b:nth-of-type(1) 也能选中 b1 盒子,因为这时 b1 已经是它的父元素下同一个标签名( p )的元素中的第 1 个了
以 .class:nth-of-type(i) 为例,大家在使用伪类选择器的时候要注意理解它的含义
个人学习笔记,如有差误欢迎指正