Child elements can be selected by using the child selector. To select all child elements recursively we can use the universal selector *
.
To select all the child elements of an element recursively in CSS, we use the following syntax:
.myDiv * {background-color: red;}
This allows us to select all the child elements, including the ones that are not explicitly stated by their name, ID, or class. In the example above, all the child elements of a div
with class myDiv
will have a red background, without us having to explicitly assign a color to each child element.
Let's explore the following example to see how the example above works:
In the index.js
file, we can see that the last two paragraph tags are not child elements of the myDiv
class.
It's worth mentioning that there is a difference between child selection vs. descendant selection. Using recursive selection, we actually select descendants of an element and not only its direct children.
Let's examine the difference between child element selection vs. the recursive selection of an element's descendants in the following example:
In the example above, we can witness the difference between direct child element selection and recursive selection in action. If we select the direct children of the .myDiv
element with the direct child selector >
, we can only select its direct children, and any deeply nested element would be ignored. For example, “Hello World” does not have a red background color in output because it's nested within a span tag. Let's see how we can select all paragraph descendants of the myDiv
class.
We use the descendant selector, .myDiv p
, which consists of the parent element and the descendant we want to select with a space between them. In the above example, the descendant selector selects all the descendants of the myDiv
class that are paragraphs, including the nested one. For example, now "Hello World" has a red background in output.
Now, let's see how the universal selector selects all the descendants of .myDiv
.
Lastly, by using the universal selector, *
, we can select all the descendants of .myDiv
without having to specify which tag (or class or ID, if we had one) we need. That's how every single element inside .myDiv
, no matter how deeply nested, will have a red background.