user11621919
user11621919

Reputation:

How can I change background color of each list item in Css?

I want to change the background-color first,fifth,seventh list item yellow and second,fourth,eighth list item green and third,sixth list item purple, How can I do it?

li:nth-child(2n+1){
    background-color: yellow;
}

Upvotes: 0

Views: 424

Answers (1)

disinfor
disinfor

Reputation: 11533

You can use the specificity and cascading rules of CSS to your advantage here:

  1. Make every element background yellow.
  2. Then target every even element - which will get you your second, fourth sixth, and eighth.
  3. Now, we can use the 3n+3 to target the third and override the sixth element from the even rule.

li {
  background-color: yellow;
}

li:nth-child(even) {
  background-color: green;
}

li:nth-child(3n+3) {
  background-color: purple;
}
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
</ul>

Upvotes: 2

Related Questions