CSS Child Combinator

Child Combinator 

The child combinator is also one of the combinators. The child combinator is used to combine the two selectors in such a way, that the elements matched by the second selector are selected only if they are direct children of the elements matched by the first selector.

This is more strict than the descendant combinator. In the descendant combinator, we are selecting the element matched by the second selector, if it is the child (any child, not necessarily direct) of the element matched by the first selector. On the other hand, the child combinator selects the element matched to the second selector, which is a direct child of the elements matched by the first selector.

Let’s now have a look at how are we going to use the child combinator with our selectors. Here is the demo –

SelectorA > SelectorB{
some properties…
}
Basically, from the above example, we can simply understand that we are using the child combinator to combine the selectors. Now here, only those elements matched to the selectorB would be selected, which are direct children of the elements matched by the selectorA.

Let’s have a look at an example, which gives us a clearer idea about the concept of a child combinator.


From the above code, we can identify that we are trying to mark only those spans, which is a direct child of div. Here, in div, we have a span that is a direct child of div, and we are having another span which is inside p, which is in turn inside a div. So, this span, which is within the paragraph, is not a direct child of div, so it won’t be styled, but the other span, which is a direct child, would be styled. Have a look at the output as well –

As you can see, only the span, which was a direct child of the div was selected and styled, while the other span was not a direct child of the div, and was not styled.

So, this was about the child combinator. We can use the child combinator as and when required. Remember that here, we are only selecting the elements matching the second selector, only if they are the direct child of the elements matching the first selector.