Introduction
The child selector helps you style only direct children of an element. It keeps your styles neat and specific.
The child selector helps you style only direct children of an element. It keeps your styles neat and specific.
parent > child {
property: value;
}The > symbol means 'direct child'.
It selects only elements that are immediate children, not deeper descendants.
ul > li {
color: blue;
}div > p {
margin-top: 1rem;
}section > h2 {
font-weight: bold;
}This example colors direct list items green and bold. Nested list items inside another list are gray and normal weight.
<!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> ul > li { color: green; font-weight: bold; } ul li li { color: gray; font-weight: normal; } </style> </head> <body> <ul> <li>Direct child item 1</li> <li>Direct child item 2 <ul> <li>Nested child item 1</li> <li>Nested child item 2</li> </ul> </li> <li>Direct child item 3</li> </ul> </body> </html>
Use the child selector to avoid styling nested elements unintentionally.
It helps keep your CSS organized and predictable.
The child selector > targets only direct children.
It is useful for precise styling in nested HTML structures.
It keeps styles from affecting deeper nested elements.
> do?> targets only elements that are direct children of a specified parent.<li> elements that are direct children of a <ul>?> symbol between parent and child tags.<li> elements directly inside <ul>, use ul > li.<div>
<p>First</p>
<section>
<p>Second</p>
</section>
</div>div > p { color: red; }<p> elements will be red?<li> children of <ol> blue:ol > li { color: blue }<li> elements inside nested <ol> too. What is the problem?<ol> inside <li> creates new direct children <li> for the inner ol.<li> get coloredol > li matches direct children of any ol, including nested ones, so all nested li get colored.<span> elements that are direct children of <div class='container'>, but not <span> inside nested elements. Which CSS selector achieves this?<span> elements directly inside <div class='container'> should be styled, excluding nested spans.> selects direct children only, so .container > span matches only spans directly inside the container div.Pass the test and this pattern moves unknown