Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

CSS Child Selector

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.

Leave a reply