CSS选择器:first-of-type失效问题排查
问题原因与解决方案
为什么:first-of-type失效?
:first-of-type的作用是匹配父元素下同类型元素中的第一个,这里的“类型”指的是HTML标签类型(比如div、p),不是class类名。
看你的HTML结构,.parentTwo下的子元素全是div标签:
- 第一个div是
.firstNested - 第二个div是
.secondNested - 第三个div是
.thirdNested - 第四个div是
.thirdNested
你的选择器.parentOne .parentTwo .thirdNested:first-of-type逻辑是:找同时满足两个条件的元素——有.thirdNested类,并且是父元素下第一个div。但父元素下第一个div是.firstNested,根本没有.thirdNested类,所以这个选择器找不到任何元素,自然不会生效。
为什么:last-of-type生效?
:last-of-type是匹配父元素下同类型元素中的最后一个,.parentTwo下最后一个div刚好是.thirdNested类,所以选择器.parentOne .parentTwo .thirdNested:last-of-type能精准匹配到这个元素,蓝色高亮也就生效了。
正确的写法
如果要选中第一个.thirdNested元素,可以用以下几种方式:
方式1:使用:nth-child选择器
直接选中.parentTwo下的第三个子元素(前两个是其他类的div):
.parentOne .parentTwo .thirdNested:nth-child(3) { color: red; }
方式2:使用兄弟选择器
选中紧跟在.secondNested后的.thirdNested(也就是第一个.thirdNested):
.parentOne .parentTwo .secondNested + .thirdNested { color: red; }
方式3:使用:nth-of-type(和:nth-child效果一致,因为子元素都是div)
.parentOne .parentTwo div:nth-of-type(3) { color: red; }
内容的提问来源于stack exchange,提问作者es3735746
相关产品推荐
相关产品推荐

