CSS Child Selector (A > B) — Direct Child Only
Learn the CSS child combinator (>) that targets only direct children of an element, not deeper descendants. Compare with the descendant selector and understand specificity.
Detailed Explanation
CSS Child Selector
The child combinator (>) selects elements that are direct children of a specified parent. Unlike the descendant combinator, it does not match elements nested deeper than one level.
Syntax
/* Select only direct <li> children of .menu */
.menu > li {
display: inline-block;
}
Direct Children vs All Descendants
<ul class="menu">
<li>Item 1</li> <!-- matched by .menu > li -->
<li>
Item 2
<ul>
<li>Sub-item</li> <!-- NOT matched by .menu > li -->
</ul>
</li>
</ul>
Why Use the Child Selector?
- Preventing style leakage — Styles intended for top-level items don’t affect nested items
- More predictable behavior — Easier to reason about which elements are affected
- Component isolation — Critical in component-based architectures
Chaining Child Selectors
You can chain multiple child selectors for precise targeting:
.sidebar > .widget > h3 {
/* Only h3 elements that are direct children of .widget,
which itself is a direct child of .sidebar */
}
Specificity
Same as descendant: the sum of all parts. .menu > li = (0, 1, 1).
Real-World Example
/* Top-level nav items are horizontal; nested items are vertical */
.nav > li { display: inline-block; }
.nav li li { display: block; }
Use Case
Child selectors are essential for multi-level navigation menus where top-level items need different styling than nested dropdown items. They prevent unintended style inheritance in component libraries, ensure layout grid items only apply to direct children (like CSS Grid and Flexbox layouts), and help maintain clean separation between parent and nested component styles.