HTML and CSS Reference
In-Depth Information
Here's another example: let's say that you want gray to be the text color of any
b
(bold-
face) element that is part of a
blockquote
, and also for any bold text that is found in a
normal paragraph:
blockquote b, p b {color: gray;}
The result is that the text within
b
elements that are descended from paragraphs or
block quotes will be gray.
One overlooked aspect of descendant selectors is that the degree of separation between
two elements can be practically infinite. For example, if you write
ul em
, that syntax
will select any
em
element descended from a
ul
element, no matter how deeply nested
the
em
may be. Thus,
ul em
would select the
em
element in the following markup:
<ul>
<li>List item 1
<ol>
<li>List item 1-1</li>
<li>List item 1-2</li>
<li>List item 1-3
<ol>
<li>List item 1-3-1</li>
<li>List item <em>1-3-2</em></li>
<li>List item 1-3-3</li>
</ol></li>
<li>List item 1-4</li>
</ol></li>
</ul>
Another, even subtler aspect of descendant selectors is that they have no notion of
element proximity. In other words, the closeness of two elements within the document
tree has no bearing on whether a rule applies or not. This has bearing when it comes
to specificity (which we'll cover later on) but also when considering rules that might
appear to cancel each other out.
For example, consider the following (which contains a selector type we'll discuss later
in this chapter):
div:not(.help) span {color: gray;}
div.help span {color: red;}
<div class="help">
<div class="aside">
This text contains <span>a span element</span> within.
</div>
</div>
What the CSS says, in effect, is “any
span
inside a
div
that doesn't have a
class
con-
taining the word
help
should be gray” in the first rule, and “any
span
inside a
div
whose
class
contains the word
help
” in the second rule. In the given markup fragment,
both
rules apply to the
span
shown.