You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套自定义元素中CSS nth-of-type/child选择器失效问题

嵌套自定义元素中:nth-child/:nth-of-type选择器失效的解决办法

你的问题出在选择器的作用对象上:每个<custom-div>都被包裹在独立的<another-div>里,对于各自的父元素<another-div>来说,它们都是唯一的子元素,所以不管用:nth-of-type(1)还是:nth-child(1),所有<custom-div>都会匹配第一个样式规则,自然全部显示1.svg。

正确的做法是先定位到第n个<another-div>,再选中它内部的<custom-div>来设置伪元素样式:

修改后的CSS代码:

another-div:nth-of-type(1) custom-div:before {content:url('1.svg');}
another-div:nth-of-type(2) custom-div:before {content:url('2.svg');}
another-div:nth-of-type(3) custom-div:before {content:url('3.svg');}

或者用:nth-child也能达到同样效果:

another-div:nth-child(1) custom-div:before {content:url('1.svg');}
another-div:nth-child(2) custom-div:before {content:url('2.svg');}
another-div:nth-child(3) custom-div:before {content:url('3.svg');}

因为<another-div>是同级的兄弟元素,:nth-of-type/:nth-child可以正确识别它们在父元素中的位置,再通过后代选择器选中内部的<custom-div>,就能给不同的伪元素设置对应图标了。

内容的提问来源于stack exchange,提问作者Noquierona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:04:57