Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to select the last n items with nth-child?

People also ask

How do I choose my last nth child?

The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child. n can be a number, a keyword, or a formula.

How do you select all child elements except last?

When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.

How do you except the last child in CSS?

:not(:last-child) The :last-child selector selects the last child. Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.


This will select the last two iems of a list:

li:nth-last-child(-n+2) {color:red;}
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>

nth-last-child sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.


:nth-last-child(-n+2) should do the trick


Because of the definition of the semantics of nth-child, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit - thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child gives you.