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

A descendant selector is used to select an element that is the descendant of one or more ancestor elements in a document tree. A descendant selector consists of two or more selectors in ancestor/descendant order, where each selector is separated by a whitespace.

As an example, the following HTMLW page contains an 'h1' element selector, a 'span' element selector, an 'h1 span' descendant selector, and a 'span h1' descendant selector. The 'h1' selector says to set the background of any h1 element to be yellow. The 'span' selector says to set the color of the text in a span element to be red. The 'h1 span' descendant selector says that if a span element has an h1 element as an ancestor, then the color of the text of this element should be blue. This is more specific that the previous 'span' selector, so this rule will override the red text with blue text if this selector is met. The final 'span h1' descendant selectors that that if an h1 element has span as an ancestor, the text of this h1 element should be colored purple. However, this does not exist in the document, so we shouldn't see any purple text.


<!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">
h1 { background: yellow; }
span { color: red; }
h1 span { color: blue; }
span h1 { color: purple; }
<h1>Howdy One</h1>
<h2>Howdy <span>Two</span></h2>
<h1>Howdy <span>Three</span></h1>

The display of this document is shown here. Notice that the 'h1 span' descendant selector results in coloring the 'Three' text blue, since this span element is a descendant of an h1 element.

descendant selector example