CSS3 Selectors :last-child

December 15, 2009

Of all the CSS3 selectors the structural pseudo-classes have to be my favourite. In particular I love :last-child selector, the :last-child CSS selector is incredibly powerful especially when positioning elements in a row, I am currently finding it incredibly useful when doing menus. Instead of providing a last class on the very last element in the row, you can now use pure CSS to achieve the same effect.

CSS 2.1

/*Each Element*
.image { margin-right: 5px; height: 20px; width: 20px; float:left; background-color: red; }
/* remove the margin on the last element so it lines up
.image.last { margin-right: 0px; }


/* parent of the image element */
.parent div:last-child { margin-right: 0px; }

The Downside

Unfortunately the bad aspect of this selector is that it does not fail gracefully. Meaning that a user in a none CSS3 compliant browser, (IE), it would fail horribly, this means that everything will be out of line.


If you look at this in anything but a browser which supports CSS3 the last element won't be red.

More Resources

  1. W3C Selectors Level 3
  2. CSS3 Compatibility Table
  3. MSDN Compatibility Table (tells you what works in IE8)
  4. Take Your Design To The Next Level With CSS3


comments powered by Disqus