Descendant Selector (CSS Selector)

    Adam Roberts
    Share

    Description

    The descendant selector matches all elements that are descendants of a specified element. The first simple selector within this selector represents the ancestor element—a structurally superior element, such as a parent element, or the parent of a parent element, and so on. The second simple selector represents the descendant element we’re trying to match.

    The combinator we use in a descendant selector is a whitespace character: a space, horizontal tab, carriage return, line feed, or form feed. Since whitespace characters are allowed around all combinators, you can include more than one whitespace character between the simple selectors in a descendant selector.

    Consider the following HTML fragment:

    <ul>
      <li>Item 1</li>
      <li>
        <ol>
          <li>Sub-item 2A</li>
          <li>Sub-item 2B</li>
        </ol>
      </li>
    </ul>

    We’ll try to match elements in the above fragment using the selector below:

    ul li {
      ⋮ declarations
    }

    This descendant selector will match all four li elements in the example HTML, because each of those elements has a ul element as its ancestor.

    We can also use descendant selectors to match the li elements within the ol in the example above:

    ul * li {
      ⋮ declarations
    }
    ul * * li {
      ⋮ declarations
    }
    ul * ol li {
      ⋮ declarations
    }
    ul li * li {
      ⋮ declarations
    }
    ul ol li {
      ⋮ declarations
    }
    ul li li {
      ⋮ declarations
    }
    ul li ol li {
      ⋮ declarations
    }

    However, there’s no way we can use descendant selectors to match only the list items in the unordered list. To do that, we’d need a child selector.

    Example

    Take a look at this example of the
    descendant selector in action:

    ul li {
      ⋮ declarations
    }

    This selector matches all li elements that are descendants of a ul element—that is, every li element that has a ul element as its ancestor.