CSS last-child(-1)

CssCss Selectors

Css Problem Overview


I am looking for a css selector that lets me select the pre-last child of list.

<ul>
     <li>1</li>
     <li>2</li>
     <li>3</li>
     <li>4</li>
     <li>5</li> <!-- select the pre last item dynamically no matter how long this list is -->
     <li>6</li>
</ul>

Static method:

ul li:nth-child(5)

Dynamic method:

ul li:last-child(-1)

which of course doesn't validate, also nth-last-child doesn't seem to provide a dynamic way.. I can fallback to javascript but I'm wondering if there is a css way I overlooked

Css Solutions


Solution 1 - Css

You can use :nth-last-child(); in fact, besides :nth-last-of-type() I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.

ul li:nth-last-child(2)

Solution 2 - Css

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHedde van der HeideView Question on Stackoverflow
Solution 1 - CssBoltClockView Answer on Stackoverflow
Solution 2 - CssDavid AllenView Answer on Stackoverflow