| Version |
|---|
| CSS1 |
| IE7+ | FF1+ | SA1.3+ | OP9.5+ |
|---|---|---|---|
| Buggy | Buggy | Buggy | Full |
Syntax
Description
This pseudo-class matches an
element only if it’s the first child element of its parent element. For
instance, li:first-child matches the first list
item in an ol or ul element. It
doesn’t match the first child of a list item.1
For example, let’s take the CSS selector mentioned above:
li:first-child {
⋮ declarations
}
And let’s apply it to the following markup:
<ul> <li>This item matches the selector li:first-child.</li> <li>This item does not match that selector.</li> <li>Neither does this one.</li> </ul>
Only the first list item element is matched.
Note that this pseudo-class only applies to elements—it doesn’t apply to anonymous boxes generated for text.
Example
This example selector matches the
first list item in an ol or ul
element:
li:first-child {
⋮ declarations
}
Compatibility
| Internet Explorer | Firefox | Safari | Opera | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 5.5 | 6.0 | 7.0 | 1.0 | 1.5 | 2.0 | 1.3 | 2.0 | 3.0 | 9.2 | 9.5 |
| None | None | Buggy | Buggy | Buggy | Buggy | Buggy | Buggy | Buggy | Buggy | Full |
In Internet Explorer 7 some SGML constructs, such as comments, are counted as elements.
Internet Explorer 7, Firefox versions up to and including 2, Safari versions up to and including 3, and Opera 9.2 continue to select an element as the first child even when another element is dynamically inserted before it.
Internet Explorer 7 and Firefox select the first SGML construct on the page (usually the doctype), even though it’s not a child of another element.
Opera 9.2 selects the root element,
html, even though it isn’t a child of another
element.
Footnotes
1 To perform that match,
you can use li>*:first-child.
User-contributed notes
- ID:
- #1
- Date:
- Wed, 06 May 2009 12:21:43 GMT
- Status:
- This note has not yet been confirmed for accuracy and relevance.
I noticed that "matches an element" in the first sentence is not quite correct. It seems that first-child is effective only when the first child element matches the selector, and is also the first element after the parent element.
For example the selector "p:first-child" doesn't work on either the <h3> or the first <p> in this html:
<div>
<h3>header</h3>
<p>first</p>
<p>second</p>
</div>
Add a note
To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.