CSS
What Does > Do in CSS? A Complete Guide to the Child Selector
When writing CSS, selecting the right elements efficiently can make a huge difference in styling and performance. The >
(greater-than symbol) is a child selector in CSS that allows you to apply styles only to direct child elements of a specified parent.
In this blog, we’ll cover:
✅ What the >
operator does in CSS
✅ The difference between child and descendant selectors
✅ Practical examples of using the child selector
What Is the >
Selector in CSS?
The child selector (>
) is used to target direct child elements of a specified parent. Unlike the descendant selector (), which selects all nested elements, the child selector applies styles only to immediate children.
Syntax:
parent > child {
property: value;
}
Example:
div > p {
color: red;
}
💡 This will apply red text color only to <p>
elements that are direct children of <div>
, ignoring deeply nested <p>
elements.
Child Selector vs. Descendant Selector
Selector | Description | Example |
---|---|---|
> (Child Selector) | Selects only direct children of an element. | div > p { color: blue; } |
(space) (Descendant Selector) | Selects all nested elements, regardless of depth. | div p { color: blue; } |
Example Comparison:
<div>
<p>Direct child</p>
<section>
<p>Nested child</p>
</section>
</div>
Using >
(Child Selector):
div > p {
color: red;
}
✅ Applies to: "Direct child"
❌ Ignores: "Nested child"
Using Descendant Selector ():
div p {
color: blue;
}
✅ Applies to both paragraphs (direct & nested).
Practical Uses of the >
Selector
1. Styling Direct Navigation Links
nav > ul {
background-color: #f4f4f4;
}
This ensures that only the direct <ul>
inside <nav>
gets the background color, avoiding unintended styling of deeply nested <ul>
elements.
2. Targeting Direct Table Rows
table > tr {
font-weight: bold;
}
This applies bold text only to rows directly inside <table>
, ignoring rows inside <tbody>
.
3. Preventing Unintended Styling on Nested Elements
.article > p {
font-size: 18px;
}
Ensures only paragraphs that are immediate children of .article
are affected.
Conclusion
The >
child selector in CSS is a powerful tool that improves precision in styling and helps avoid unintended inheritance. By using it effectively, you can keep your styles clean, efficient, and easy to manage.