ealione
ealione

Reputation: 1636

Understanding some nth-child examples

I am learning CSS and i was doing some experiments with nth-child. Lets say i have the code:

<html>
  <head>
    <style>
      div p:nth-child(n+3) 
      {
        color: red;
      } 
    </style>
  </head>

  <body>
    <div>
      <h1>Title</h1>
      <p> 1</p>
      <p> 2</p>
      <p> 3</p>
      <p> 4</p>
      <p> 5</p>
      <p> 6</p>
      <p> 7</p>
      <p> 8</p>
    </div>  
  </body>
</html>
  1. Why does it start coloring the elements starting from <p>2</p> when i specified that i want it to count only <p> elements (can you even do that)?

  2. Lets say that i have another element same as the other one with 8 <p> elements in it, How can i specify that i want only the 5th <p> element of the 2nd <div> element?

Upvotes: 0

Views: 51

Answers (1)

BoltClock
BoltClock

Reputation: 723729

  1. The <h1> shares the same <div> parent as the <p> elements (in other words, the <h1> and <p> elements are siblings of one another). That makes the <h1> the first child, and thus the first <p> becomes the second child, the second <p> becomes the third child (at which point :nth-child(n+3) starts matching elements), and so on.

    For elements that differ by tag name, you can use :nth-of-type() instead:

    div p:nth-of-type(n+3) 
    {
      color: red;
    }
    
  2. Like so:

    div:nth-child(2) p:nth-of-type(5) 
    {
      color: red;
    }
    

    Again, if there are any other siblings among the <div> elements, :nth-child() will not work as you expect. You can always replace it with another :nth-of-type() like so:

    div:nth-of-type(2) p:nth-of-type(5) 
    {
      color: red;
    }
    

Upvotes: 3

Related Questions