0
0
CssHow-ToBeginner · 3 min read

How to Use Descendant Selector in CSS: Simple Guide

The CSS descendant selector targets elements that are inside another element, no matter how deep. You write it by placing a space between two selectors, like parent child, which styles all child elements inside parent elements.
📐

Syntax

The descendant selector uses a space between two selectors. The first selector matches the ancestor element, and the second matches any element inside it, at any depth.

  • ancestor descendant: selects all descendant elements inside ancestor elements.
css
ancestor descendant {
  /* CSS properties */
}
💻

Example

This example styles all span elements inside div elements by making their text red. It shows how the descendant selector applies styles to nested elements.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Descendant Selector Example</title>
<style>
div span {
  color: red;
  font-weight: bold;
}
</style>
</head>
<body>
  <div>
    <p>This is a paragraph with a <span>red span inside a div</span>.</p>
    <span>This span is also red.</span>
  </div>
  <p>This <span>span is not red</span> because it is outside the div.</p>
</body>
</html>
Output
A webpage showing a paragraph inside a div with a red bold span, a red bold span directly inside the div, and a normal black span outside the div.
⚠️

Common Pitfalls

Common mistakes when using descendant selectors include:

  • Using no space, which selects only direct children (child selector >), not descendants.
  • Expecting the selector to style elements outside the ancestor.
  • Overusing descendant selectors which can slow down rendering if too general.
css
/* Wrong: no space means direct child only */
div>span {
  color: blue;
}

/* Right: space means any descendant */
div span {
  color: red;
}
📊

Quick Reference

SelectorMeaningExample
ancestor descendantSelects all descendants inside ancestordiv span
ancestor > childSelects only direct childrendiv > span
elementSelects all elements of this typespan
.classSelects all elements with this class.highlight

Key Takeaways

Use a space between selectors to target all nested elements with the descendant selector.
Descendant selector matches elements at any depth inside the ancestor.
Do not confuse descendant selector with child selector which uses > for direct children only.
Avoid overly broad descendant selectors to keep CSS efficient.
Descendant selectors help style nested HTML elements clearly and simply.