How to Use Child Selector in CSS: Simple Guide
The CSS
child selector uses the symbol > to select only direct child elements of a parent. For example, div > p targets all p elements that are immediate children of a div, ignoring deeper nested p elements.Syntax
The child selector uses the > symbol between two selectors. The first selector is the parent, and the second is the direct child.
- Parent > Child: Selects only elements that are direct children of the parent.
- It does not select grandchildren or deeper descendants.
css
parent > child {
/* styles here */
}Example
This example shows how to color only paragraphs that are direct children of a div. Nested paragraphs inside other elements are not affected.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Child Selector Example</title> <style> div > p { color: blue; font-weight: bold; } </style> </head> <body> <div> <p>This paragraph is a direct child of div and will be blue.</p> <section> <p>This paragraph is nested inside section, so it will not be blue.</p> </section> </div> <p>This paragraph is outside div and will not be blue.</p> </body> </html>
Output
A page showing one blue bold paragraph inside the div, one normal paragraph nested inside section, and one normal paragraph outside the div.
Common Pitfalls
Many beginners confuse the child selector > with the descendant selector (space). The child selector only targets immediate children, not all nested elements.
Also, using the child selector with incorrect parent or child selectors can cause no elements to be styled.
css
/* Wrong: selects all nested paragraphs inside div, not just direct children */ div p { color: red; } /* Correct: selects only direct child paragraphs of div */ div > p { color: blue; }
Quick Reference
parent > child: Selects direct children only.parent child: Selects all descendants (children, grandchildren, etc.).- Use child selector to apply styles precisely to immediate children.
Key Takeaways
Use the > symbol to select only direct child elements in CSS.
Child selector ignores nested grandchildren or deeper descendants.
Do not confuse child selector (>) with descendant selector (space).
Child selector helps apply styles precisely to immediate children.
Check your selectors carefully to avoid styling no elements.