Child selector
Lesson 7 of 15 in Coddy's CSS Selectors course.
A child selector is a type of CSS selector that selects all elements that are direct children of a specified element. The child selector is denoted by a greater-than sign (>) between two selectors.
Example:
Consider the following HTML structure:
<div class="parent">
<p>This is a direct child paragraph.</p>
<div>
<p>This is an indirect child paragraph.</p>
</div>
</div>To target the direct child paragraph, you would use the child combinator as follows:
.parent > p {
color: blue;
}In this example, only the direct child paragraph will turn blue, not the one nested inside the inner <div>.
Child selectors can also be used to avoid styling elements that are not direct children of a specified element. For example, you could use a child selector to style all links that are direct children of a p element to be red.
Challenge
EasyGiven the following HTML structure, create a CSS rule using the child combinator to style the direct list items inside the <ul> element to have a background color of yellow.
Try it yourself
<html>
<head>
<title>Child Selector Exercise</title>
<style>
/* CSS Code goes here */
</style>
</head>
<body>
<ul class="list">
<li>This is a direct list item.</li>
<div>
<li>This is an indirect list item.</li>
</div>
</ul>
</body>
</html>All lessons in CSS Selectors
3Combinator Selectors
Child selectorDescendant selectorAdjacent sibling selectorGeneral sibling selector