
First child selectors select a specified element if, and only if, it is the first element contained by its parent element. It doesn't matter what this parent element is.
The first child selector has a syntax much like a pseudo-element selector (it's not a pseudo element however because while the first-line or the first-letter of an element are not actually HTML elements, the first-child is itself an HTML element). The syntax is a selector (commonly, but not necessarily a simple HTML element selector), followed by :first-child
For example p:first-child selects any paragraph when it is the first element contained by its parent.
Consider the following situation
<div class="introduction">
<p>...</p>
<p>...</p>
</div>
The first-child selector above will only select the first paragraph in the div.
On the other hand it will not select anything in the code below.
<div class="introduction">
<table>...</table>
<p>...</p>
</div>
In this second example the table element is the first child.
Think of the following scenario. We have each chapter of a book as a web page. Where the chapter is divided into sections, we have created a div. Within these divs we have the content of our chapter in paragraphs. Commonly, the first paragraph of a section appears differently from the remainder of the paragraphs of the section. With CSS1, we could add a special class, say first-paragraph and mark up each of the first paragraphs in the HTML using this class. With CSS2, we can use first child selectors to save us the trouble. This also means if the chapter is later edited, to remove certain paragraphs, or rearrange their order, we needn't re-edit the source of the HTML. Further, by marking up each first paragraph as being of class first-paragraph, we are subtly introducing appearance into our HTML, which as we have seen is to be avoided.
By way of example, the selector for the above selection of each paragraph when it is a first child would be p:first-child.
| Internet Explorer | Netscape Navigator | Opera | WebTV | ||||||||
| Windows | Macintosh | (All Platforms) | (All Platforms) | ||||||||
| 4.0 | 5.0 | 5.5 | 6.0 | 4.0 | 4.5 | 5.0 | 4.x | 6.0 | 3.5 | 5.0 | 1.0 |
| N | N | N | N | N | N | Y | N | Y | N | N | N |