Menu
Coddy logo textTech

Descendant selector

Lesson 8 of 15 in Coddy's CSS Selectors course.

In the previous topic, we learned about the child combinator, which targets direct children of an element. Now, let's explore descendant selectors, which are denoted by whitespace. A descendant selector allows you to target elements that are nested inside another element at any level, not just direct children.

Syntax

selector1 selector2 {
  /* property declarations */
}

For example,

<html>
<head>
  <title>Combinator</title>
  <style>
    div p {
      color: red;
      font-size: 2em;
    }
  </style>
</head>
<body>
  <div>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
  </div>
</body>
</html>

The CSS rule above will style both paragraphs red and have a font size of 2em.

 

How does it relate to child selectors?

A descendant selector is more general than a child selector. This means that a descendant selector will match all elements that are descendants of a specified element, while a child selector will only match elements that are direct descendants of a specified element.

For example, the selector div p will match all p elements that are descendants of a div element, including p elements that are nested within other p elements. The selector div > p will only match p elements that are direct descendants of a div element.

challenge icon

Challenge

Easy

Building upon the previous exercise, let's use the same HTML structure. Write a CSS rule using the descendant selector to style all paragraphs inside the .list element, regardless of their level of nesting. Give them a new color, size and font as you see fit

Try it yourself

<html>
<head>
    <title>Descendant Selector Exercise</title>
    <style>
        /* CSS Code goes here */
    </style>
</head>
<body>
<div>
    <p>This paragraph is not inside a list</p>
    <ul class="list">
        <li>
            <p>This is a paragraph inside a list item.</p>
        </li>
        <li>
            <div>
                <p>This is a paragraph inside a nested div within a list item.</p>
            </div>
        </li>
    </ul>
</div>
</body>
</html>

All lessons in CSS Selectors