How do I use the first-child pseudo-class?
Author: Deron Eriksson
Description: This CSS tutorial describes how to use the first-child pseudo-class.
Tutorial created using: Windows XP

The :first-child pseudo-class can be used to select the first child element of another element. The :first-child pseudo-class is used by appending it to the child element in the selector.

In the style-test.html file below, we have two rules that use the :first-child pseudo-class. The first rule states that for the first div element that is the child of another element, the text should be italicized. The second rule states that for the first span that is a child of another element, we should make its text bold.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Style Test</title>
<style type="text/css">
body { background-color: aqua; margin: 0; }
div:first-child { font-style: italic; }
span:first-child { font-weight: bold; }
<div>This line is italicized since it belongs to the first div.
	<span>This is bold since it is the first span.</span>
	<span>This is not bold.</span>
<div>This line isn't italicized since it belongs to the second div.</div>

The display of the style-test.html page in IE7 is shown below. The :first-child pseudo-class also works fine in Firefox, but it does not work in IE6. In the results, we can see that all text within the first div element (which is a child of the body element) is italicized. In addition, the text of the first span element (which is a child of the first div element) is bold.

:first-child pseudo-class example