Using CSS pseudo-class’ :first-child and :last-child
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:
1 2 3 4 5 6 |
<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.
1 2 3 4 5 6 |
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.
3 Comments
raghvenra
thees effects r relay cool
Keshav Naidu
Hi Paul,
Your HTML and CSS is not matching.
HTML is tags.
CSS is P tag styles.
Just wanted to inform you.
Thanks 🙂
Paul Robinson
Hi Keshav,
I’m not sure I follow? The HTML & CSS demo use the tags they are supposed to.