Descendant selectors are used to select elements that are descendants of another element in the document tree.
For example, you may wish to target a specific <em> element on the page, but not all <em> elements. A sample document could contain the following code:
<body>
<h1>Heading <em>here</em> </h1>
<p>Lorem ipsum dolor <em>sit</em> amet.</p>
</body>
The document tree diagram (with the <em> element to be targeted) would be:
If you use a type selector like the example below, you will select all <em> elements on the page:
em {color: blue; }
However, if you use a descendant selector, you can refine the <em> elements that you select. The rule below will only select <em> elements that are descendants of <p> elements. If this rule is applied, the <em> element within the <h1> will not be colored blue.
p em {color: blue; }
You can also jump levels in the document tree structure to select descendants. For example, the following code:
<body>
<p>Lorem ipsum dolor <em>sit</em> amet.</p>
<ul>
<li>item 1</li>
<li>item 2</li>
<li><em>item 3</em></li>
</ul>
</body>
The document tree (with a third-level <em> element highlighted) would be:
Using the following rule you can isolate any <em> element inside a <ul> element, without having to describe the <li> element. If this rule is applied, any <em> element within a <ul> element will be colored blue. However, the <em> element within the <p> will not be colored blue:
ul em {color: blue; }
Descendant selectors are well supported across standards-compliant browsers.