Search code examples
htmlcsscss-selectorspseudo-class

How to include more tags inside nth-child()


I have some doubts about using nth-child. I would like to understand if it is possible to include multiple tags inside nth-child() instead of writing them each time. For example, I have 6 elements and I want to include the 2nd and 3rd element in nth-child to apply a class that changes background color.

I've tried blindly with nth-child(2, 3) but obviously it doesn't work. Then I looked at some references and realized that nth-child(n+otherNumber) can be used but I couldn't get it to work.

In addition to understanding how to sequentially include multiple tags, I would also like to understand how to include tags fired together, such as 3 and 5.

I'm relatively new to all of this, can anyone clarify? I appreciate any response, thanks for any help.

div.modal-content > p:nth-child(2) {
  background-color: red;
}
<div class="modal-content">
  <span class="close-button">Button Example</span> <!-- Is this counted as element 1 ? -->
  
  <p> 
  Element 2
  </p>

  <p>
  Element 3     
  </p>

  <p>
   Element 4
  </p>

  <p>
  Element 5
  </p>

  <p>
  Element 6
  </p>    
</div>


Solution

  • As said in the comments, you can not include multiple numbers with a comma, but you can do this:

        div.modal-content>p:nth-child(2), p:nth-child(3) {
            background-color: red;
        }