skip to Main Content

I am creating a layout with custom elements inside custom elements and having problems with css:nth. I am adding icons in content:before but they all display the same icon. Here is the code

First try CSS code, using 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');}

Second try CSS code, using 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');}

Here is the 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>

As you can see, what I want is to display icons different icons to each custom-div, but the only result I am getting is that the same icon 1.svg is being displayed for all 3 custom divs. no matter what I do

EDIT: forgot to say that the custom-div is inside another-div both with custom elements names

2

Answers


  1. The problem is that you are using :nth-of-type on the child component (custom-div) itself rather than on the parent component (another-div)

    This should work for you:

    another-div:nth-of-type(1) custom-div::before {
    content: url("https://img.cdn4dd.com/s/media/photosV2/1954ba82-d91f-43a2-8838-767fd2ad386f-retina-large.svg");
    }
    
    another-div:nth-of-type(2) custom-div::before {
    content: url("https://img.cdn4dd.com/s/media/photosV2/edf12308-afd7-427e-b4d4-7e78c3efce01-retina-large.svg");
    }
    
    another-div:nth-of-type(3) custom-div::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>
    Login or Signup to reply.
  2. I found another way to do it an addition to @TanishqS.

    You can still use the custom-div with:

    another-div:nth-of-type(1) custom-div::before { content: url("https://placehold.co/50"); }
    another-div:nth-of-type(2) custom-div::before { content: url("https://placehold.co/80"); }
    another-div:nth-of-type(3) custom-div::before { content: url("https://placehold.co/100"); }
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search