How do I use child selectors?
Author: Deron Eriksson
Description: This CSS example demonstrates child selectors.
Tutorial created using: Windows XP


A child selector is used to select an element that is a child of another element. It is similar to a descendant selector except that descendant selectors apply to ancestor/descendant relationships, and child selectors apply to parent/child relationships. The parent and child elements in a child selector are separated by a greater than sign (>).

As an example, consider the following HTMLW page. It features a child selector, 'h2>span', and a descendant selector, 'h1 span'. The child selector selects a span element that is a child of an h2 element. Its declaration specifies to color such a selection red. The descendant selector selects a span element that is a descendant of an h1 element. Its declaration specifies to color such a selection blue.

style-test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Style Test</title>
<style type="text/css">
h2>span { color: red; }
h1 span { color: blue; }
</style>
</head>
<body>
<h2>Howdy <span>One</span></h2>
<h2>Howdy <strong><span>Two</span></strong></h2>
<h1>Howdy <span>Three</span></h1>
<h1>Howdy <strong><span>Four</span></strong></h1>
</body>
</html>

The HTML page is shown in IE7 below. Notice that 'One' is red 'Two' is not, since the first matches the 'h2>span' child selector, but the second doesn't since the strong element gets in the way. Notice that both 'Three' and 'Four' are blue, since both elements match the 'h1 span' descendant selector.

child selectors example

In my cross-browser testing, Firefox and IE7 properly handle child selectors, but IE6 does not handle child selectors, although IE6 does handle descendant selectors.