CSS Child Selector

We use the CSS child selector to target the elements that are direct children of a specific element. To indicate this, we use the (>) symbol between the selectors.

The basic syntax is as follows:

parent_selector1 > child_selector2 { style_properties }

As you can see the child selector is very similar to the css descendant selector, but it is more restrictive.

Let’s say we have this html code:

<div>
<ul>
<li>Unordered list item</li>
<li>Unordered list item</li>
<li>Unordered list item</li>
</ul>
<div>
<ul>
<li>Unordered list item</li>
<li>Unordered list item</li>
<li>Unordered list item</li>
</ul>
</div>
</div>

So here we have a div that contains an unordered list and within that div we have another div with another unordered list.

We add a default text color to the body:

body {
   color: black;
}

So all list item is black now. We could use the descendant selector to change the color of the list items like this:

div ul li {
   color: green;
}

Now all list items are green. But what if I want a different color for the second unordered list? Here is where the child selector comes in:

div > div ul li {
   color: red;
}

 

Now the second unordered list is red. We have overwritten the rules of the descendant selector.

Check the full code on Codepen.

ChristianKovats
ChristianKovats

Christian Kovats is a London-based web designer who loves crafting innovative and user-friendly interfaces. His passion for design is only rivaled by his love for nature and hiking, often drawing inspiration from his treks through the diverse landscapes of the UK. Outside of work, Christian enjoys spending quality time with his wife and 4-year-old son. A seasoned lucid dreamer, he also spends time exploring the intricate world of dream interpretation, reflecting his ever-curious and creative mind.

ChristianKovats

Leave a reply

You must be logged in to post a comment.