CSS :first-child and :last-child selectors
Posted January 2nd, 2010 in HTML and CSS (Updated September 26th, 2011)
The CSS selectors :first-child and :last-child are used to apply styling to the first and last child elements of the parent. :first-child is part of the CSS 2.1 specification and :last-child CSS 3 so support is slightly limited for :first-child and more limited for :last-child. A number of browsers also have issues applying the styling correctly after additional elements have been added dynamically.
HTML/CSS Example
The following example makes the the first <p> in #example have a yellow background and the last <p> in #example have blue text:
<style type="text/css">
#example p:first-child {
background-color: yellow;
}
#example p:last-child {
color: blue;
}
</style>
<div id="example">
<p>This is the first child</p>
<p>This is the second child</p>
<p>This is the third child</p>
<p>This is the last child</p>
</div>
Just defining "p:first-child { ... }" would work the same, i.e. the containing element does not need to be included in the declaration, but it would then apply the styling to all <p> tags that are the first child of an element. In the above example it will only apply the styling to the first <p> child of #example.
Example in action
Here's the HTML and CSS from above working in action, and be sure to note the browser compatibilty information below.
This is the first child
This is the second child
This is the third child
This is the last child
Browser compatibility
Internet Explorer 6 has no support for either.
IE7 and IE8 both support :first-child and not :last-child but a <!DOCTYPE> must be specified.
Both work in all versions of Firefox. I have tested Chrome for Windows, Opera 9.64 and Safari 3 and 4 for Windows and they all work in those versions.
Please note as per the first paragraph of this post that there can be issues updating the styles of first-child and last-child when additional elements are added dynamically.
Useful :nth-child Recipes
As well as first-child and last-child, there's nth-child which gives a lot of control over styling child selectors. Supported in all modern browsers (IE from 9+ only). I've summarized a post by Chris Coyier here, with a direct link to the source article here.
Related posts:
- Useful :nth-child Recipes (Monday, September 26th 2011)
- "Clearing" floats with overflow: auto (Saturday, January 9th 2010)
- Using ellipsis with HTML and CSS (Saturday, December 5th 2009)
- Starting an HTML ordered list with a number other than 1 (Saturday, October 10th 2009)
- Using CSS letter-spacing to space out titles (Saturday, April 18th 2009)
- Using !important with CSS (Saturday, January 31st 2009)

Comments
blog comments powered by Disqus