1

Having difficulty trying to target a particular element in a set that is the last matching selector.

<div class="items">
    <article class="today">
        this is today
    </article>
    <article class="today">
        this is today
    </article>
    <article class="today">
        this is today
    </article>
    <article>
        Not today
    </article>
    <article>
        Not today
    </article>
</div>

My goal is to re-style the last item article.today.

article {
    background: cyan;
}

.today:last-child { 
    background: black;
    color: white;
}

it does not work. http://jsfiddle.net/nv54h/ changing to:

article {
    background: cyan;
}

article:last-child { 
    background: black;
    color: white;
}

does work in that last item is now black. http://jsfiddle.net/nv54h/1/ - but without doing two loops or different elements, I can't get it to work as expected (via eg, last-of-type)

is there any way you can think of targetting the last .today item only? list is generated via iteration of a collection on the fly that changes in real time so a CSS/markup only solution would be perfect, avoiding logic and back references if item n+1 not today etc. I guess :last in Sizzle is an ideal solution but...

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69
  • 3
    `:last-child` applies only for elements and not classes and hence the first option doesn't work :) You can refer to my answer [**here**](http://stackoverflow.com/questions/18995362/css-last-child-not-working-as-expected/18995451#18995451) or BoltClock's answer I have linked in that. – Harry Jul 15 '14 at 15:05

1 Answers1

1

The only way I can think of doing this is with javascript...

:last-child and :last-of-type only work on elements, they don't pay attention to classes in the way you are thinking they should. By removing the two articles without a class name your code then works...

http://jsfiddle.net/nv54h/2/


Using some jQuery you can achieve this easily:

$( "article.today:last" ).css({ backgroundColor: "yellow", fontWeight: "bolder" });

http://jsfiddle.net/nv54h/3/


Better yet, just add a class. This way, all your styles can remain in your style sheet.

$( "article.today:last" ).addClass('black');

http://jsfiddle.net/nv54h/4/

Michael
  • 7,016
  • 2
  • 28
  • 41
  • …but even when using JS, please set classes instead of inline stylesheets. That way you may edit all the required CSS in one place. – feeela Jul 15 '14 at 15:18
  • yeah I ended up decorating the last element matching with a class. it's not ideal but it works. – Dimitar Christoff Jul 17 '14 at 08:19