Descendant and child combinators
Definition and purpose
Combinators describe relationships between elements. The descendant combinator (whitespace) matches a target anywhere below an ancestor. The child combinator (>) requires the target to be a direct child. The right-hand selector identifies the elements being styled.
Descendants at two depths
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>.panel p { color: navy; }</style> </head> <body> <section class="panel"> <p id="a">Direct</p> <div> <p id="b">Nested</p> </div> </section> <p id="c">Outside</p> </body></html>Both paragraphs inside panel match; the outside paragraph stays unchanged.
Syntax and mental model
nav a selects links at any depth inside nav. nav > a selects only links whose immediate parent is nav. Indentation and visual layout do not determine parentage: the HTML element tree does. Spaces around > are optional. An ancestor need not be the immediate parent.
Direct children only
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>.panel > p { color: green; }</style> </head> <body> <section class="panel"> <p id="a">Direct</p> <div> <p id="b">Nested</p> </div> </section> </body></html>Only the direct paragraph matches.
Common mistakes
Do not use a descendant selector when nested components must remain independent. Test a direct child and a nested child in the same fixture.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Selector lists and compound selectors. Next lesson: Sibling combinators.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Descendant and child combinators — knowledge check
Five questions on descendant and child combinators.
Which selects all links inside nav at any depth?
Which selects only direct links?
In .panel > p, what is styled?
If a p is inside div inside section, does section > p match it?
What determines a direct-child relationship?