CSS pseudo classes can be extremely useful. In this little tip I am going to go through exactly how to use the first-child & last-child pseudo classes.

In CSS :first-child & :last-child do exactly what they say. They select the first HTML element & the last HTML element within an element. Take this HTML:

<div>
    <span>Span 1</span>
    <span>Span 2</span>
    <span>Span 3</span>
    <span>Span 4</span>
</div>

In this example the first child is ‘span 1′ and the last child is ‘span 4′. You can use this feature to highlight the first paragraph (similar to the first paragraph of this post) without having to apply a class to the first tag, or you can round the edges of the first & last navigation items in a menu. Really the ideas are limitless.

The is one tiny, little caveat though… Alright so it’s actually a huge one. Neither work in IE6 (do we really care anymore?), and last-child doesn’t work in IE7, and Safari 3.0. Oh well, at least you can still use first-child.

Example

Here is a simple example.

p:first-child {
    color: red;
}
p:last-child {
   text-decoration: underline;
}

Here is the result:

This is the first paragraph.

This is a second.

This is the last one.

I hope you enjoyed this little CSS tip. Let me know if you have any questions, or if you have anything to add (like compatibility info etc) please drop it in the comments.