How to Select Direct Children Only in CSS: Simple Guide
Use the CSS child combinator
> to select only direct children of an element. For example, parent > child targets elements that are immediate children of parent, ignoring deeper nested descendants.Syntax
The child combinator selector uses the > symbol between two selectors. It matches only elements that are direct children of a specified parent.
parent > child: Selects allchildelements that are immediate children ofparent.parent: The parent element selector.child: The child element selector.
css
parent > child {
/* styles here */
}Example
This example shows how to style only the direct li children of a ul. Nested li inside another ul will not get the style.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Direct Children CSS Example</title> <style> ul > li { color: blue; font-weight: bold; } </style> </head> <body> <ul> <li>Direct child 1</li> <li>Direct child 2 <ul> <li>Nested child 1</li> <li>Nested child 2</li> </ul> </li> <li>Direct child 3</li> </ul> </body> </html>
Output
A bulleted list where 'Direct child 1', 'Direct child 2', and 'Direct child 3' are bold and blue, but 'Nested child 1' and 'Nested child 2' are normal black text.
Common Pitfalls
Many beginners confuse the child combinator > with the descendant selector (a space). The descendant selector matches all nested elements, not just direct children.
Wrong example: div p styles all p inside div, even deeply nested ones.
Right example: div > p styles only p elements that are immediate children of div.
css
/* Wrong: styles all paragraphs inside div, including nested */ div p { color: red; } /* Right: styles only direct child paragraphs of div */ div > p { color: green; }
Quick Reference
Remember these tips when using the child combinator:
- Use
>to target only immediate children. - Use a space to target all descendants at any depth.
- Combine with other selectors for precise targeting.
- Works with any element types, classes, or IDs.
Key Takeaways
Use the child combinator
> to select only direct children in CSS.The descendant selector (space) selects all nested elements, not just direct children.
Direct children selectors help avoid styling unintended nested elements.
Combine
> with classes or element names for precise styling.Always test your selectors to ensure they target the correct elements.