T K T K - 2 months ago 7
CSS Question

select the element before the last using nth child regardless of how many elements you have?

Ok, so I was reading http://css-tricks.com/how-nth-child-works/ (and looking around the web) about the :nth-child pseudo class and I can’t find anything related to the issue I have:

Is there a way to select, for example, the element before the last regardless of how many elements you have?

For example: I have a list of horizontal links in a nav bar, but I need to select the one before the last one regardless of how many links I have in that nav bar.

Does this make sense? Can that be done using the :nth-child pseudo class?… or in any other way for that matter?

I’ve been cracking my head with this one for several days already.

Thanks.

Answer

You can use :nth-last-child(2):

li:nth-last-child(2) {
  color: red;
}

li:nth-last-child(2) {
  color: red;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

About :nth-last-child:

The :nth-last-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings after it in the document tree, for a given positive or zero value for n, and has a parent element.

In effect, it functions the same as :nth-child except it selects items counting backwards from the end of element series, not the start.