how to use the last-child for the penultimate too?

6

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

I know I can use the last-child selector for the last, but the penultimate selector? How do I do?

    
asked by anonymous 23.08.2016 / 15:45

1 answer

4

If you are wanting to capture the last and second-to-last 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>
    
23.08.2016 / 15:57