CSS 第 n 个类型或子元素无法与另一个自定义元素内的自定义元素一起使用

问题描述 投票:0回答:1

我正在创建一个在自定义元素内包含自定义元素的布局,并且遇到 css:nth 问题。我在 content:before 添加图标,但它们都显示相同的图标。这是代码

首先尝试 CSS 代码,使用 nth-of-type(number):

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

第二次尝试CSS代码,使用child(number):

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

这是 HTML

<another-div><custom-div> text 1 </custom-div></another-div>
<another-div><custom-div> text 2 </custom-div></another-div>
<another-div><custom-div> text 3 </custom-div></another-div>

如您所见,我想要的是为每个自定义 div 显示不同的图标,但我得到的唯一结果是为所有 3 个自定义 div 显示相同的图标 1.svg。不管我做什么

编辑:忘了说自定义 div 位于另一个具有自定义元素名称的 div 中

html css
1个回答
0
投票

问题是您在子组件 (

:nth-child
) 本身而不是父组件 (
custom-div
) 上使用
another-div

这应该适合你:

another-div:nth-of-type(1)::before {
  content: url("https://img.cdn4dd.com/s/media/photosV2/1954ba82-d91f-43a2-8838-767fd2ad386f-retina-large.svg");
}

another-div:nth-of-type(2)::before {
  content: url("https://img.cdn4dd.com/s/media/photosV2/edf12308-afd7-427e-b4d4-7e78c3efce01-retina-large.svg");
}

another-div:nth-of-type(3)::before {
  content: url("https://img.cdn4dd.com/s/media/photosV2/0d63d52b-ff6f-4c39-8b52-f6c605ce38dc-retina-large.svg");
}
<another-div>
  <custom-div> text 1 </custom-div>
</another-div>
<another-div>
  <custom-div> text 2 </custom-div>
</another-div>
<another-div>
  <custom-div> text 3 </custom-div>
</another-div>

© www.soinside.com 2019 - 2024. All rights reserved.