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 (not necessarily a type selector), followed by
p:first-child selects any paragraph when it is the first element contained by its parent.
Consider the following situation
first-child selector above will only select the first paragraph in the
On the other hand it will not select anything in the code below.
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
<div>s 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. One thing we could do is add a special class, say
first-paragraph and mark up each of the first paragraphs in the HTML using this class. But better, we can use first child selectors to save us the trouble - we don't need to make any changes to the HTML at all. This also means if the chapter is later edited, to remove certain paragraphs, or rearrange their order, we needn't re-edit the source. 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