Descendent Selectors in CSS

CSS descendant selectors allow you to apply styles to elements that are nested inside other elements. This targeting method helps create specific styling rules without affecting similar elements elsewhere on the page.

Syntax

ancestor descendant {
    property: value;
}

The descendant selector uses a space between two selectors to target elements that are children, grandchildren, or any level deep within the ancestor element.

Example: Styling Emphasized Text in Lists

Apply yellow color to <em> elements only when they appear inside <ul> tags:

<!DOCTYPE html>
<html>
<head>
<style>
ul em {
    color: #FFFF00;
}

ol strong {
    color: #808000;
}
</style>
</head>
<body>
    <ul>
        <li>This is <em>emphasized text</em> in unordered list</li>
        <li>Another item with <em>yellow emphasis</em></li>
    </ul>
    
    <ol>
        <li>This is <strong>strong text</strong> in ordered list</li>
        <li>Another <strong>olive-colored strong</strong> text</li>
    </ol>
    
    <p>This <em>emphasized text</em> is NOT in a list, so no yellow color.</p>
    <p>This <strong>strong text</strong> is NOT in ordered list, so no olive color.</p>
</body>
</html>

How It Works

The descendant selector ul em targets any <em> element that appears anywhere inside a <ul> element, regardless of how deeply nested it is. Similarly, ol strong targets <strong> elements within <ol> elements.

Multiple Level Descendant Example

<!DOCTYPE html>
<html>
<head>
<style>
div p span {
    background-color: #FFE4B5;
    padding: 2px;
}
</style>
</head>
<body>
    <div>
        <p>This paragraph contains a <span>highlighted span</span> element.</p>
        <div>
            <p>Nested div with <span>another highlighted span</span>.</p>
        </div>
    </div>
    
    <p>This <span>span is NOT highlighted</span> because it's not inside a div.</p>
</body>
</html>

Key Points

  • Descendant selectors use spaces to separate ancestor and descendant elements
  • The descendant can be at any nesting level within the ancestor
  • More specific selectors have higher priority than general ones
  • Descendant selectors help avoid applying styles to unintended elements

Conclusion

Descendant selectors provide precise control over element styling by targeting elements within specific containers. Use them to create focused styling rules that only affect elements in particular contexts.

Updated on: 2026-03-15T23:18:59+05:30

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements