of-type选择器的坑

first-of-type, last-of-type, nth-of-type, nth-last-of-type 选择器的用法和我们想象的不一样,可以说是不合常理
它们的用法相同,就以 nth-of-type 举例

:nth-of-type(1) 选择同类型标签元素的第1个

p:nth-of-type(1) 用法合乎常理,就是第一个p元素

.class:nth-of-type(1) 用法就变了,并不是.class的第一个,而是 具有.class, 且是 同类型标签的第一个,极有可能匹配不到任何元素

of-type 选择器始终匹配标签类型的第几个,挺坑的

要实现选择第1个.class,可以使用 nth-child 的 of 语法

:nth-child(1 of .item){
    color: red
}

也可以使用更复杂的选择器

:nth-child(1 of p.item){
    color: red
}

目前兼容性 chrome 111,safari 9

posted @ 2023-05-30 14:46  全玉  阅读(33)  评论(0编辑  收藏  举报