Say I have a list as follows:
Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3.
Cheers!
The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
The :last selector selects the last element. Note: This selector can only select one single element. Use the :last-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the last element in a group (like in the example above).
nth-child() is a very handy pseudo-selector, but sometimes you need to approach things from the other end, starting from the last item. That's where nth-last-child comes to the rescue.
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)
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With