嵌套自定义元素中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
相关产品推荐
相关产品推荐

