CSS Descendant Combinator

The CSS descendant combinator is used to apply styles to elements that are nested within another element. This combinator is represented by a space between two selectors and targets elements that are descendants of a specified parent element.

The syntax for the descendant combinator is:

</>
Copy
selector1 selector2 {
    property: value;
}

Where:

ParameterDescription
selector1The parent selector.
selector2The child or descendant selector.
propertyA CSS property (e.g., color, margin, etc.).
valueThe value assigned to the CSS property.

Examples

Styling Paragraphs Inside Divs using Descendant Combinator

In this example, we style all <p> elements that are descendants of <div> elements, setting their text color to blue.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        div p {
            color: blue;
        }
    </style>
</head>
<body>
    <div>
        <p>This paragraph is inside a div.</p>
    </div>
    <p>This paragraph is not inside a div.</p>
</body>
</html>

Styling List Items Inside an Unordered List using Descendant Combinator

Here, we style all <li> elements that are descendants of <ul>, setting their font weight to bold.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        ul li {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
    <ol>
        <li>This item is in an ordered list.</li>
    </ol>
</body>
</html>

Styling Specific Descendant Elements using Descendant Combinator

In this example, we style all <span> elements that are descendants of <div> elements, adding a background color of lightgray.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        div span {
            background-color: lightgray;
        }
    </style>
</head>
<body>
    <div>
        <span>This is a span inside a div.</span>
    </div>
    <span>This span is not inside a div.</span>
</body>
</html>