CSS Child Combinator
The CSS child combinator (>) is used to select elements that are direct children of a specified parent element. This combinator is stricter than the descendant combinator as it only applies styles to immediate child elements.
The syntax for the child combinator is:
</>
Copy
selector1 > selector2 {
property: value;
}
Where:
| Parameter | Description |
|---|---|
selector1 | The parent element. |
selector2 | The immediate child element. |
property | A CSS property (e.g., color, margin, etc.). |
value | The value assigned to the CSS property. |
Examples
Styling Immediate Child Paragraphs using Child Combinator
In this example, we style all <p> elements that are direct children of <div>, setting their text color to blue.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div > p {
color: blue;
}
</style>
</head>
<body>
<div>
<p>This paragraph is a direct child of the div.</p>
<div>
<p>This paragraph is nested inside another div.</p>
</div>
</div>
</body>
</html>
Styling Direct List Items using Child Combinator
Here, we style all <li> elements that are direct children of <ul>, setting their font weight to bold. Nested <li> elements are not affected.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
ul > li {
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Nested Item 1</li>
</ul>
</li>
</ul>
</body>
</html>
Styling Immediate Child Divs using Child Combinator
In this example, we apply a border to <div> elements that are direct children of another <div>.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div > div {
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div>
<div>This is a direct child div.</div>
<div>
<div>This is a nested child div.</div>
</div>
</div>
</body>
</html>
