Home > Blockchain >  How to select specific type of child which has other types of siblings in CSS
How to select specific type of child which has other types of siblings in CSS

Time:02-18

I want to add background color to only group 3

.group {
  border: 1px solid black;
}

.parent .group:nth-child(3) {
  background: red;
  /*not working*/
}

.parent .group:nth-of-type(3) {
  background: red;
  /*not working*/
}
<ul >
  <li >Group 1</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 2</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Item 3</li>
  <li >Item 4</li>
  <li >Group 3</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 4</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 5</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 6</li>
  <li >Item 1</li>
  <li >Item 2</li>
</ul>

CodePudding user response:

nth-child doesn't work because it still refers to the nth-child of the parent. So .parent .group:nth-child(3) would refer to "item 2" because its the third child of .parent. Your best bet would properly be to add a specific class to the element you want to style.

CodePudding user response:

I found this way is working fine.

Instead of targeting the 3rd child, use the 9th child. I don't have the best explanation of what is going on but I think the nth-child() is referring to the li in ul.

.group {
  border: 1px solid black;
}

.parent .group:nth-child(3) {
  background: red;
  /*not working*/
}

.parent .group:nth-of-type(3) {
  background: red;
  /*not working*/
}

.parent .group:nth-child(9) {
  background: red;
  /*working*/
}
<ul >
  <li >Group 1</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 2</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Item 3</li>
  <li >Item 4</li>
  <li >Group 3</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 4</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 5</li>
  <li >Item 1</li>
  <li >Item 2</li>
  <li >Group 6</li>
  <li >Item 1</li>
  <li >Item 2</li>
</ul>

  • Related