Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of selecting the last item of a list with CSS?

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!

like image 413
Marcel Avatar asked Sep 09 '08 03:09

Marcel


People also ask

How do you target the last item in a list CSS?

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.

How do you choose the last element?

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

How do I get the last two elements in CSS?

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.


3 Answers

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)

like image 68
Glenn Slaven Avatar answered Oct 19 '22 10:10

Glenn Slaven


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.

like image 23
Bobby Jack Avatar answered Oct 19 '22 09:10

Bobby Jack


The answer for this question should be updated! IE9 + Firefox (for a while back) + Chrome, Safari all support: last-of-type or last-child

like image 30
OZZIE Avatar answered Oct 19 '22 10:10

OZZIE