Home / CSS :first-child and :last-child selectors

CSS :first-child and :last-child selectors

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).