2

I have a number of elements with specific css class on the page (let's say item). Is it possible to apply a css style on the (N-1)th .item? For example it there are 9 elements then I need to style 8th.

I know about :nth-last-child(2). But it doesn't work in my case. It searches for CHILD elements but in my case elments are distributed between different parents.

jsFiddle of what I need

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153

2 Answers2

4

use the child combinator selector (>) with body along with @Zenith's solution

body > :nth-last-child(2)

http://jsfiddle.net/fWRw8/2/

MikeM
  • 27,227
  • 4
  • 64
  • 80
3

Yes, you can use the :nth-last-child(2) selector to get the second-last element.

Here's a jsFiddle example.

This isn't supported in older versions of IE, so here's a link to a quick hack which will get it working there too.


Edit: In regard to your specific use case, sadly it looks like there isn't any real solution using just CSS. My initial thoughts were :nth-last-of-type but as you're basing it on a class and with different parents that won't work. :nth-last-child is also based on the parent so that won't help either. Sadly, there is no class-related selectors similar to these either so I'm afraid to say you may have to do it via. jQuery.

Community
  • 1
  • 1
dsgriffin
  • 66,495
  • 17
  • 137
  • 137