UPDATE: The fiddle link I posted has the working code now. :not(:last-child)
and :nth-last-child(n + 2)
both work perfectly.
I'm trying to use the nth-child
or nth-last-child
selector to select every li
in a ul
except for the last one. The catch is, the length of the list can vary from 1 to 5 elements. I haven't been able to find any documentation or examples of how to accomplish this.
Here is the HTML for the 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 element in the list. I've also tried the code below, but that doesn't select anything. I tried a number of other combinations as well, but they either didn't work at all or selected the last element.
ul > li:nth-child(1):nth-last-child(2) > a:hover {
color: red;
}
Here is a fiddle.
Use :not(:last-child)
to target all except the last.
http://jsfiddle.net/96nd71e3/1/
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>
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