CSS nth-child selects everything except the last element when length is unknown

UPDATE: the link to the fiddle that I posted now has working code. :not(:last-child) and :nth-last-child(n + 2) work fine.

I am trying to use the nth-child or nth-last-child selector to select every li in ul , except for the last. Catch - the list length can vary from 1 to 5 elements. I could not find any documentation or examples of how to do this.

Here is the HTML for ul :

 <ul class="breadcrumbs"> <li> <a href="/">Home</a> </li> <li> <a href="/categories/1">Articles</a> </li> <li> <a href="/categories/6">Specials</a> </li> <li class="current"> <a href="/categories/6/articles/21">Song Lyrics</a> </li> </ul> 

Here is my current code:

 ul > li:nth-last-child(-1n+4) > a:hover { color: red; } 

This code still selects the last item in the list. I also tried the code below, but that doesnโ€™t select anything. I also tried a number of other combinations, but they either didn't work at all, or they chose the last item.

 ul > li:nth-child(1):nth-last-child(2) > a:hover { color: red; } 

Here is the fiddle .

+8
css css-selectors
source share
3 answers

Use :not(:last-child) to target all but the last.

http://jsfiddle.net/96nd71e3/1/

+28
source share

Use :nth-last-of-type or :nth-last-child

http://jsfiddle.net/t0k8gp4d/

 li:nth-last-of-type(n + 2) a { color: red; } 
 <ul class="breadcrumbs"> <li> <a href="/">Home</a> </li> <li> <a href="/categories/1">Articles</a> </li> <li> <a href="/categories/6">Specials</a> </li> <li class="current"> <a href="/categories/6/articles/21">Song Lyrics</a> </li> </ul> 
+4
source share

You can use this

 <ul class="breadcrumbs"> <li> <a href="/">Home</a> </li> <li> <a href="/categories/1">Articles</a> </li> <li> <a href="/categories/6">Specials</a> </li> <li class="current"> <a href="/categories/6/articles/21">Song Lyrics</a> </li> </ul> 

CSS

 ul > li{ background:red; } ul > li:last-child{ background:black; } 

But if you absolutely need to change your style outside of the main li element, use this

 ul > li{ background:black; } ul > li:not:last-child{ background:red; } 
0
source share

All Articles