15

If a ul has li items with multiple classes, is it possible to get the last item of a specific class using :last-child?

For example, consider following:

<ul class="test">
    <li class="one">
    <li class="one">
    <li class="one">
    <li class="two">
    <li class="two">
</ul>

I want to add some style to the last li having class "one" (ie. third in the list).

I tried following and it does not work.

ul.test li.one:last-child 
user1355300
  • 4,867
  • 18
  • 47
  • 71
  • 1
    I think you haven't searched for it that much? http://stackoverflow.com/questions/6401268/how-do-i-select-the-last-child-with-a-specific-class-name-in-css – paddotk Jul 04 '12 at 10:14
  • Same question but (some) different answers. There is value in repetition!! – gonzo Nov 12 '14 at 14:02

3 Answers3

26

That's not possible yet.

  • :last-child selects the last child, regardless of the tag name, etc.
  • The possible alternative, :last-of-type selects the last occurrence of a tag. It ignores the class name, etc.

Your only option is to add a specific class name to that element, or use JavaScript to add this class name.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks but how the :last-of-type will work in above html example? – user1355300 Jul 04 '12 at 10:21
  • @user1355300 It won't work as expected. In your example, there's only one type of child, namely `
  • `. So, `:last-child` and `:last-of-type` selects the same element (the 5th `
  • `). See http://jsfiddle.net/vEphZ/
  • – Rob W Jul 04 '12 at 10:28
  • I know this is an old question, but for future viewers, I think Rob W got the answer right but forgot to put it wholly. This: `ul.test > li:last-of-type` should work to select only the last item in the test list – flen Jun 30 '17 at 01:24