Search code examples
htmlcsscss-selectorspseudo-class

how to pick second element starting from the last one?


enter image description here

I have two elements and they have the same class and I want to pick the second element starting from the last one. ( I hope image tells you everything)

I tried nth-child but my two elements have same class which is why I can't do with nth-child any idea ?


Solution

  • you can use nth-last-child(2) or nth-last-of-type(2), this will select the 2nd last item.

    li {
      display: inline-block
    }
    li:nth-last-child(2) {
      color: red
    }
    <ul>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
    </ul>
    <hr />
    <ul>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
    </ul>