Search code examples
htmlcsscss-selectorspseudo-class

"nth-last-child(1)" not targeting last element


I am not fully understanding the behaviour of some css pseudo class selectors.

Looking at this simple html template:

 <body>

  <div>
   <p>One</p>
   <p>Two</p>
  </div>

  <div>
   <p>Three</p>
   <p>Four</p>
  </div>

  <div>
   <p>Five</p>
   <p>Six</p>
  </div>

  <div>
   <p>Seven</p>
   <p>Eight</p>
  </div>

 </body>

I do not understand why the following css would actually apply the style to the first div:

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

and the following css won't apply the style to the last div:

div:nth-last-child(1){
 color: red;
}

As far as I understand the nth-child selector will find the target, look for his parent and select the nth-child corresponding to the target.

Thanks for your help.

Andrea


Solution

  • The problem with div:nth-last-child(1) is that the last div is not the last child.

    Some IDEs, such as jsFiddle, insert a script element in the document tree.

    enter image description here

    That script element is being targeted by :nth-last-child(1), which doesn't care about element type. It only looks at siblings.

    You have to either:

    1. get rid of the script element

    2. use div:nth-last-child(2)

    3. use div:nth-last-of-type(1)

    jsFiddle demo