Combinators: Descendant and Child
You'll learn how to select elements based on their parent-child relationships using two essential CSS combinators.
What Are Combinators?
In CSS, combinators let you select elements based on how they relate to other elements in your HTML structure. Think of them as family relationships: you can target "all grandchildren" or "only direct children" of a particular element.
The Descendant Combinator (Space)
The space character selects any nested element, no matter how deeply buried:
article p {
color: blue;
}
This targets every <p> inside an <article>, whether it's a direct child or nested inside other elements like <div> or <section>.
Analogy: Like saying "all descendants in my family tree" — children, grandchildren, great-grandchildren, etc.
The Child Combinator (>)
The > symbol selects only direct children:
article > p {
color: red;
}
This targets only <p> elements that are immediate children of <article>, not those nested deeper.
Analogy: Like saying "only my children, not my grandchildren."
Quick Comparison
nav a { } /* All links anywhere inside nav */
nav > a { } /* Only links directly inside nav */
If you have <nav><ul><li><a>, the first rule matches the <a>, but the second doesn't (because <a> isn't a direct child of <nav>).
Key Takeaway: Use the space combinator to select all descendants at any depth, and the > combinator when you need to target only direct children—giving you precise control over element relationships.