1

I am trying to set a background different for each item-icon but it selects every elements instead of the first:

CSS part

.dropdown-item-icon {
  width: 50px;
  height: 50px;
  border-radius: 5px;

  &:nth-child(1) {
    background-color: red;
  }
}

HTML part with items and items icons:

<div class="dropdown">
  <a href="">
    <div class="dropdown-item">
      <div class="dropdown-item-icon"></div>
      <div class="dropdown-item-info">
        <span class="name">Browse</span>
        <p class="description">Challenges created by the community</p>
      </div>
    </div>
  </a>
  
  <a href="">
    <div class="dropdown-item">
      <div class="dropdown-item-icon"></div>
      <div class="dropdown-item-info">
        <span class="name">My List</span>
        <p class="description">Joined and created challenges</p>
      </div>
    </div>
  </a>
</div>
Geeky Quentin
  • 2,469
  • 2
  • 7
  • 28
TDev
  • 75
  • 1
  • 10

1 Answers1

1

It doesn't work because the pseudo selection nth-child only tries to match the immediate nth child of a parent element. Here, you are trying to get the first child of .dropdown-item-icon which gets you the immediate first child of its parent which is dropdown-item.

It works only when both of the .dropdown-item-icon are children of the same parent which is not the case here. However, .dropdown-item-icon is a child of .dropdown-item which is a child of the a tag. Both of the a tags are children of the container .dropdown. Hence to get the first .dropdown-item-icon, get the first a tag.

a:first-child .dropdown-item .dropdown-item-icon {
  background-color: red;
}

Take a look at the following code snippet:

.dropdown-item-icon {
  width: 50px;
  height: 50px;
  border-radius: 5px;
}

a:first-child .dropdown-item .dropdown-item-icon {
  background-color: red;
}
<div class="dropdown">
  <!-- parent child -->
  <a href="">
    <div class="dropdown-item">
      <div class="dropdown-item-icon"></div>

      <div class="dropdown-item-info">
        <span class="name">Browse</span>
        <p class="description">Challenges created by the community</p>
      </div>
    </div>
  </a>

  <!-- parent-child -->
  <a href="">
    <div class="dropdown-item">
      <div class="dropdown-item-icon">

      </div>
      <div class="dropdown-item-info">
        <span class="name">My List</span>
        <p class="description">Joined and created challenges</p>
      </div>
    </div>
  </a>
</div>
Geeky Quentin
  • 2,469
  • 2
  • 7
  • 28