Is it possible to target the very last list element in CSS?

css, html-lists

Solution

The CSS3 Way (IE9+)

If you know exactly how deep your last item is, you can repeat your calls to `:last-child`:

li:last-child li:last-child {
    color: red;
}

This pseudo-class selector isn't supported in IE prior to version 9, according to http://caniuse.com/#search=last-child. Of course, if you don't know how deep this list item will be, then this method isn't really helpful.

The JavaScript Way

You can target the very last list item via JavaScript as well:

var items = document.getElementById("mylist").getElementsByTagName("li"),
    _item = items[ items.length - 1 ];

_item.className == "" 
  ? _item.className = "last" 
  : _item.className += " last" ;

This is raw JavaScript, which requires no additional frameworks or libraries. If you're using a popular framework like jQuery, this could be even simpler:

$("#mylist li:last").addClass("last");

I wouldn't suggest you use jQuery just for something like this. Raw JavaScript would be far faster, and far less bloat.

The Preprocessor way

Depending on how your navigational menu is constructed, you may be able to use a server-side language to identify the last list-item, and mark it as such. For example, we could perform the following using the `DOMDocument` class in PHP:

$d = new DOMDocument();
$d->loadHTML( $html );
    
$a = $d->getElementsByTagName("li");
$l = $a->item( $a->length - 1 );

$c = $l->getAttribute("class");

empty( $c ) 
  ? $l->setAttribute("class", "last") 
  : $l->setAttribute("class", "last $c");

echo $d->saveHTML( $l );

This finds the last list item in the HTML and adds a new class of "last" to it. The benefit to this is that it doesn't require complicated, and often times poorly-supported, CSS3 selectors. Further, it doesn't require the addition of large JavaScript libraries to do trivial things.

Problem

I have a page menu being generated that will be similar in structure to the following nested list: ``` <ul> <li>Page 1</li> <li>Page 2</li> <li> Page 3 <ul> <li>Subpage 1</li> <li>Subpage 2</li> <!-- Can I target ONLY this element? --> </ul> </li> </ul> ``` Note that this list is dynamic. The number of items and number of levels are not predictable. So, something like this wouldn't be flexible enough: ``` /* I know this does not have great browser support - just an example */ ul > li > ul > li:last-child { /* CSS here */ } ``` I realize that I could modify my server code to add a class to the last item, but I would first like to know if this is possible in CSS. To make matters more complicated, I would like to target all major browsers along with IE 7+. Is it possible to target the very last list item using CSS? Basically, I need this Fiddle solved (via @Pumbaa80).

Original source