I am wondering if there is some way to change a CSS attribute for the last li
in a list using CSS. I have looked into using :last-child
, but this
:last-child is CSS3 and has no IE support while :first-child is CSS2, I believe the following is the safe way to implement it using jquery
$('li').last().addClass('someClass');
$('li').last().addClass('someClass');
if you have multiple
I usually do this by creating a htc file (ex. last-child.htc):
<attach event="ondocumentready" handler="initializeBehaviours" />
<script type="text/javascript">
function initializeBehaviours() {
this.lastChild.className += ' last-child';
}
</script>
And call it from my IE conditional css file with:
ul { behavior: url("/javascripts/htc/last-child.htc"); }
Whereas in my main css file I got:
ul li:last-child,
ul li.last-child {
/* some code */
}
Another solution (albeit slower) that uses your existent css markup without defining any .last-child class would be Dean Edwards ie7.js library.
If you know there are three li's in the list you're looking at, for example, you could do this:
li + li + li { /* Selects third to last li */
}
In IE6 you can use expressions:
li {
color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}
I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child
selector gets better support.