Episode 14 of 53

Descendant Selectors

Learn how to target elements nested inside other elements with descendant selectors.

A descendant selector targets elements that are nested inside another element, at any depth. You write two or more selectors separated by a space.

Syntax

/* Target all <a> tags inside a <nav> */
nav a {
    color: white;
    text-decoration: none;
}

/* Target all <li> inside a <ul> with class "menu" */
.menu li {
    list-style: none;
    padding: 0.5rem;
}

Any Depth

Descendant selectors match at any nesting level, not just direct children:

<div class="card">
    <div class="body">
        <p>This paragraph IS matched by .card p</p>
    </div>
</div>
.card p {
    color: gray;
    /* Matches the p even though it is nested inside .body */
}

Multiple Levels

/* Target spans inside list items inside nav */
nav li span {
    font-weight: bold;
}

Tips

  • Keep descendant selectors short (2-3 levels max)
  • Very long selectors are fragile and slow
  • Prefer classes over deep nesting for better maintainability