XML technologies / CSS / Advanced websites with CSS / Behind the scenes / Selectors and CSS rule structure / Selector for descendants

(Excerpt from “CSS − Advanced websites with Cascading Stylesheets” by Rachel Andrew & Dan Shafer)

Recall that in an HTML document’s inheritance hierarchy, every HTML element except html is a descendant of at least one other HTML element. A descendant selector (English: descendant selector) lets you assign style rules that apply only to elements below a particular element in the inheritance chain.

A descendant selector, as in the following example, restricts a style rule to descendants of other elements. Its scope is determined by the HTML elements listed in the rule, separated by spaces and read from left to right.

li em {
  color: green;
}

This style rule gives green text to all words inside tags <em></em>. However, it applies only when em is a descendant of a list item.

In the following example, the text inside the first tags <em></em> is green, but the text inside the second tags <em></em> is not, because the element em is not a descendant of an element li.

<ul>
  <li>Erster Eintrag</li>
  <li><em>Zweiter</em>Eintrag</li>
</ul>
<p>Ein Wort in <em>Kursivschrift</em>.</p>

With descendant selectors, inheritance need not occur between immediate parent and child elements; it can span several levels.

<div class="seitenleiste">
  <p>Falls Sie Fragen haben, <a href="contact.html">rufen Sie unser Büro während der Geschäftszeiten an</a>.</p>
</div>

The following style rule therefore also applies to the element a, which is an immediate child of the element p but a second-generation descendant of the element div:

div a {
  font-style: italic;
}

  

 

 

 

back to top