Is there a way of selecting the last item of a list with CSS?
-
09-06-2019 - |
Question
Say I have a list as follows:
- item1
- item2
- item3
Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3.
Cheers!
Solution
Not that i'm aware of. The traditional solution is to tag the first & last items with class="first" & class="last" so you can identify them.
The CSS psudo-class first-child will get you the first item but not all browsers support it. CSS3 will have last-child too (this is currently supported by Firefox, Safari but not IE 6/7/beta 8)
OTHER TIPS
Until it's properly supported, you'll need to add a class to 'last' items, as suggested. You don't have to do this manually, though. If you can take a javascript hit, take a look at either:
- the jQuery :last-child selector
- Keeping Your Elements’ Kids in Line with Offspring (a list apart article by Alex Bischoff), a specific, lighter-weight method
Either will avoid 'polluting' your markup, and are perfectly acceptable if your style is a 'nice addition' as opposed to a 'must have' design feature.
The answer for this question should be updated! IE9 + Firefox (for a while back) + Chrome, Safari all support: last-of-type
or last-child