475

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;
}
johannchopin
  • 11,813
  • 8
  • 41
  • 91
clarkk
  • 25,706
  • 67
  • 182
  • 315

2 Answers2

758

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

johannchopin
  • 11,813
  • 8
  • 41
  • 91
anroesti
  • 10,531
  • 3
  • 20
  • 33
  • 1
    it works, but now it overrides all other classes even if they have a higher priority.. (they are placed later in the css file) – clarkk Feb 05 '11 at 22:33
  • The selector also plays a role in what priority the properties have, not just where in the file they appear. You could try adding ` !important` to your values, e.g. `color: red !important;` – anroesti Feb 05 '11 at 22:39
  • I know, it's a bit ugly. You could instead try writing more precise selectors, chances are, this would work too. (e.g. `#head ul` → `#head ul#navi`) – anroesti Feb 05 '11 at 22:46
  • I don't think I get it :) could you please do a better example? – clarkk Feb 05 '11 at 22:49
  • 2
    Okay, very basic example: `p.xy` is more important than `p`, because it is kind of more specific. http://jsfiddle.net/ftJVX/ – anroesti Feb 05 '11 at 22:55
  • 2
    what if I want all child that had a specific class? – MEM May 07 '14 at 15:13
  • How to use hover state for these elements 'div.dropdown *:hover' does not work – Jithin Jose Sep 22 '14 at 05:36
  • @MEM try this: p .childWithClass. Jithin Jose are all * selector elements the same elements? if so, try div.dropdown element:hover. see http://allcssselectors.com – user3339411 Feb 17 '15 at 22:11
  • I think with a good CSS structure inheritance should do the work in itself. – Webwoman Aug 12 '19 at 17:44
189

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 > * 
Manu Artero
  • 7,807
  • 5
  • 54
  • 65
Abdennour TOUMI
  • 76,783
  • 33
  • 229
  • 231