Select all child elements recursively in CSS

CssCss Selectors

Css Problem Overview


How can you select all child elements recursively?

div.dropdown, div.dropdown > * {
    color: red;
}

This class only throws a class on the defined className and all immediate children. How can you, in a simple way, pick all childNodes like this:

div.dropdown, 
div.dropdown > *, 
div.dropdown > * > *, 
div.dropdown > * > * > *, 
div.dropdown > * > * > * > * {
    color: red;
}

Css Solutions


Solution 1 - Css

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

Solution 2 - Css

The rule is as following :

A B {
  /* B is descendant of A */
}
A > B {
  /* B is direct child of A */
}

So

div.dropdown *

instead of

div.dropdown > * 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclarkkView Question on Stackoverflow
Solution 1 - CssanroestiView Answer on Stackoverflow
Solution 2 - CssAbdennour TOUMIView Answer on Stackoverflow