CSS Descendant Selector

The CSS Descendant Selector selects elements that are located anywhere inside another specified element. It works with both direct children and deeply nested descendants.

A descendant selector uses a space between two selectors. It is useful when you want to style particular elements inside a section, container, or other HTML element without affecting matching elements elsewhere on the page.

CSS Descendant Selector Syntax

The syntax for a descendant selector is:

parent descendant {
    property: value;
}

The first selector identifies the parent or ancestor, while the second identifies the elements to style inside it.

CSS Descendant Selector Example

<!DOCTYPE html>
<html>
<head>
    <title>CSS Descendant Selector</title>
    <style>
        article p {
            color: blue;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <article>
        <h2>CSS Tutorials</h2>
        <p>This paragraph appears blue.</p>

        <div>
            <p>This nested paragraph also appears blue.</p>
        </div>
    </article>

    <p>This paragraph remains unchanged.</p>
</body>
</html>

In this example, article p selects every <p> element inside an <article>, including paragraphs nested inside other elements. The paragraph outside the article is not affected.

Using Class Selectors with Descendant Selectors

You can combine descendant selectors with classes to target specific parts of a webpage.

<div class="content">
    <h2>Learn CSS</h2>
    <p>Explore CSS tutorials.</p>
</div>

<p>This paragraph is outside the content section.</p>
.content p {
    color: green;
}

Only paragraphs inside the element with the content class receive green text.

Learn more about CSS Class Selectors and CSS Selectors.

Descendant Selector vs. Child Selector

The descendant selector uses a space, while the child selector uses the greater-than symbol (>).

article p {
    color: blue;
}

article > p {
    color: red;
}

The first rule selects all paragraphs inside an article, at any nesting level. The second selects only paragraphs that are direct children of the article.

Explore our upcoming CSS Child Selector tutorial to understand this difference in detail.

When to Use CSS Descendant Selectors

Descendant selectors are useful for styling paragraphs inside articles, links inside navigation menus, or headings inside particular content sections. They help you target elements based on their position within the HTML structure without adding extra classes or IDs.