Home > Articles

Selectors in Action

  • Print
  • + Share This
This chapter is from the book

Descendant Selectors

Descendant selectors are used to select elements that are descendants of another element.

For example, in the HTML sample shown in Listing 3.1, three <a> elements are descendants of the <li> elements. To target these three <a> elements only, and not all other <a> elements, a descendant selector can be used as shown in Listing 3.6. This selector targets any <a> element that is nested inside an <li> element.

Listing 3.6 CSS Code Containing Descendant Selector

li a
{
 color: green;
}

Descendant selectors do not have to use direct descendant elements. For example, the <a> element is a descendant of <div id="nav"> as well as the <li> element. This means that #nav a can be used as a selector as well (see Listing 3.7).

Listing 3.7 CSS Code Containing Descendant Selector

#nav a
{
 color: red;
}

Descendant selectors also can include multiple levels of descendants to be more specific as shown in Listing 3.8.

Listing 3.8 CSS Code Containing Descendant Selector

#nav ul li a
{
 color: green;
}
  • + Share This
  • 🔖 Save To Your Account