| Version |
|---|
| CSS1 |
| IE5.5+ | FF1+ | SA1.3+ | OP9.2+ |
|---|---|---|---|
| Buggy | Full | Full | Full |
Syntax
Description
The descendant selector matches all elements that are descendants of a specified element. The first simple selector within this selector represents the ancestor element—a structurally superior element, such as a parent element, or the parent of a parent element, and so on. The second simple selector represents the descendant element we’re trying to match. If you’re a little unclear about the terms ancestor element and descendant element, have a look at CSS Layout and Formatting for a complete explanation.
The combinator we use in a descendant selector is a whitespace character: a space, horizontal tab, carriage return, line feed, or form feed. Since whitespace characters are allowed around all combinators, you can include more than one whitespace character between the simple selectors in a descendant selector.
Consider the following HTML fragment:
<ul>
<li>Item 1</li>
<li>
<ol>
<li>Sub-item 2A</li>
<li>Sub-item 2B</li>
</ol>
</li>
</ul>
We’ll try to match elements in the above fragment using the selector below:
ul li {
⋮ declarations
}
This descendant selector will match all four
li elements in the example HTML, because each of those
elements has a ul element as its ancestor.
We can
also use descendant selectors to match the li elements
within the ol in the example above:
ul * li {
⋮ declarations
}
ul * * li {
⋮ declarations
}
ul * ol li {
⋮ declarations
}
ul li * li {
⋮ declarations
}
ul ol li {
⋮ declarations
}
ul li li {
⋮ declarations
}
ul li ol li {
⋮ declarations
}
However, there’s no way we can use descendant selectors to match only the list items in the unordered list. To do that, we’d need a child selector.
Example
Take a look at this example of the descendant selector in action:
ul li {
⋮ declarations
}
This selector matches all li elements that
are descendants of a ul element—that is, every
li element that has a ul element as
its ancestor.
Compatibility
| Internet Explorer | Firefox | Safari | Opera | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 5.5 | 6.0 | 7.0 | 1.0 | 1.5 | 2.0 | 1.3 | 2.0 | 3.0 | 9.2 | 9.5 |
| Buggy | Buggy | Buggy | Full | Full | Full | Full | Full | Full | Full | Full |
In Internet Explorer
5.5 and 6, this combinator doesn’t work after a :hover
pseudo-class.
In Internet Explorer 6 and 7, if there’s only a comment—without any additional whitespace—between two simple selectors, that comment is incorrectly treated as a descendant selector, when in fact it should fail.
User-contributed notes
Add a note
To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.