Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

:last-child / last-of-type pseudo difficulties

:last-child / last-of-type pseudo difficulties

Problem

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

this is today this is today this is today Not today Not today

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...

Problem courtesy of: Dimitar Christoff

Solution

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/

Solution courtesy of: Michael

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

:last-child / last-of-type pseudo difficulties

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×