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.
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.
: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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With