CSS
CSS Direct Child Selector (>): What It Is and How to Use It
The direct child selector in CSS is a powerful way to target elements that are immediate children of a specified parent. It gives you more precise control over your styling by ensuring that only the first-level elements are affected—ignoring deeper nested ones.
In this blog post, you’ll learn:
- What the direct child selector (
>
) is - How it differs from other CSS selectors
- Practical examples and use cases
✅ What Is the Direct Child Selector?
The >
selector in CSS targets only the direct (immediate) children of an element.
📌 Syntax:
parent > child {
/* styles */
}
- The child must be one level deep inside the parent to be selected.
🎯 Basic Example
✅ HTML:
<div class="parent">
<p>Direct child</p>
<div>
<p>Nested child</p>
</div>
</div>
✅ CSS:
.parent > p {
color: red;
}
✅ Result:
Only the first <p>
(directly inside .parent
) turns red.
The nested <p>
inside the <div>
stays unaffected.
🔄 Direct Child vs. Descendant Selector
It’s easy to confuse >
with the space () selector.
Selector | Meaning |
---|---|
.parent > p | Only direct children <p> |
.parent p | All <p> inside .parent (any depth) |
Example:
/* All <p> elements inside .parent, even deeply nested */
.parent p {
color: blue;
}
/* Only direct <p> children of .parent */
.parent > p {
color: red;
}
💡 Practical Use Cases
1. Styling Direct Menu Items
<ul class="menu">
<li>Home</li>
<li>About
<ul><li>Team</li></ul>
</li>
</ul>
.menu > li {
font-weight: bold;
}
✅ Only top-level items (Home
, About
) are bold—submenus remain normal.
2. Target First-Level Headings in a Section
<section class="content">
<h2>Main Heading</h2>
<div>
<h2>Sub Heading</h2>
</div>
</section>
.content > h2 {
text-transform: uppercase;
}
✅ Only the first h2
gets capitalized.
3. Custom Grid or Layout Rules
.container > div {
padding: 10px;
border: 1px solid #ccc;
}
✅ Avoids padding nested <div>
elements deeper inside other components.
🧠 Summary
Feature | Use |
---|---|
> selector | Targets only direct (immediate) children |
Improves precision | Avoids applying styles to nested elements |
Common use cases | Menus, grids, section headers, layouts |
✅ Final Thoughts
The CSS direct child selector (>
) is an essential tool for precision styling. It helps you apply styles exactly where needed—especially when working with complex layouts, menus, and reusable components.
By mastering this selector, you’ll write cleaner, more maintainable CSS and avoid unwanted side effects caused by overly broad rules.