how to use last-Child for the penultimate as well?

Asked

Viewed 5,066 times

9

I want to make a selection with css for last and penultimate item.

I know I can use the dial last-child to the last, but the penultimate? how do I?

1 answer

9


If you want to capture the last and the penultimate element, use nth-last-child(-n+2):

ul.test li {
  padding:10px;
  background-color: pink;
  list-style:none;
}

ul.test li:nth-last-child(-n+2) {
  background-color: #ddd;
}
<ul class="test">
  <li>primeiro</li>
  <li>segundo</li>
  <li>terceiro</li>
  <li>penúltimo</li>
  <li>último</li>
</ul>

To capture only the penultimate use nth-last-child(2):

ul.test li {
  padding:10px;
  background-color: pink;
  list-style:none;
}

ul.test li:nth-last-child(2) {
  background-color: #ddd;
}
<ul class="test">
  <li>primeiro</li>
  <li>segundo</li>
  <li>terceiro</li>
  <li>penúltimo</li>
  <li>último</li>
</ul>

  • 1

    I think your example would be clearer with something in the first items (<li>first</li> <li>second</li> ...)

  • @Marco edited, friend. Thanks for the tip

  • Hit miseravi!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.