Descendant Combinator CSS

Descendant Combinator

As the name says, this is a combinator, which means that we are going to combine the selectors. Here, we are going to combine the selectors such that the elements matching the second selector are only selected if there is some element matching the first selector, which is the ancestor of the second element.

If this confuses you, let’s understand this thing with help of an example. But before we move to some example, understand that the descendant combinator is represented by a single space character(“ ”).

The selectors that utilize the descendant combinator are called descendant selectors.

First of all, let’s have the syntax for how are we going to utilize the descendant combinator.

SelectorA SelectorB{
some properties…

So, as you can see, there are two selectors, separated with a space. Here, we are utilizing the descendant combinator, to combine the two selectors. So, these two selectors are combined such that, the elements matching with the selectorB are only selected if they are childs of the selectorA.(so, selectorA may be parent of parent of parent of parent of parent of… and so on… of SelectorB)

Lets have a look at an example, which helps us get the concept of the descendant combinators –

Have a look at the below program –

As you can see, in the above example, we have utilized the descendant combinator. All we are saying is that we are going to apply the mentioned style to all the spans which are childs of div. So, those spans which are not child of div, would not be selected and styled in this situation.

As we can see, there is a span, which is the child of div, so it would be styled in this situation. On the other hand, there is another span, which is not the child of any div, so it won’t be styled.

Let’s have a look at the output so that we can better understand this thing.

As you can see, only the text of that span, which is the child of div, is green, while the other is not. Using the descendant combinator is pretty much useful at times when we need to select some element only when it is the child of something. You can consider trying some other examples. You can play with it more, in order to get familiar with the concept.

Note that the descendant combinator is denoted and given with a space. Do not give a comma there, since it would cause the grouping of the selectors. In the above example, if we group the selectors, we are simply saying that I want to apply the styles to both the selectors, which is not desired for now, since we want to style only those elements matching selectorB, which are child of selectorA. So, be careful about that.