Brought to you by Style Master CSS editor

first child selectors

Explanation

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.

Syntax

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.

Use

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.

Browser support

Detailed browser support information for this feature can be found in the full version of the Westciv CSS Guide, or in our CSS Browser Support Table.

next: adjacent selectors