Using CSS pseudo-class’ :first-child and :last-child

/ CSS / by Paul Robinson / 3 Comments
This post was published back on March 31, 2010 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

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.

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.

3 Comments

Author’s gravatar

Hi Paul,
Your HTML and CSS is not matching.
HTML is tags.
CSS is P tag styles.

Just wanted to inform you.
Thanks 🙂

Reply
Author’s gravatar author

Hi Keshav,

I’m not sure I follow? The HTML & CSS demo use the tags they are supposed to.

Older Comments
Newer Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more