Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS nth-child select all but last element when length is unknown

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.

like image 239
Daniel Bonnell Avatar asked Jan 16 '15 22:01

Daniel Bonnell


2 Answers

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

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

like image 147
nickford Avatar answered Oct 22 '22 19:10

nickford


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>
like image 4
Joseph Marikle Avatar answered Oct 22 '22 19:10

Joseph Marikle