HTML and CSS Reference
In-Depth Information
Note the presence of the tilde ( ~ ) in the selector. It is the key to selection based on the
presence of a space-separated word within the attribute's value. If you omit the tilde,
you would have an exact value matching attribute selector, as discussed in the previous
This selector construct is equivalent to the dot-class notation discussed earlier in the
chapter. Thus, p.warning and p[class~="warning"] are equivalent when applied to
HTML documents. Here's an example that is an HTML version of the “PlanetML”
markup seen earlier:
<span class="barren rocky">Mercury</span>
<span class="cloudy barren">Venus</span>
<span class="life-bearing cloudy">Earth</span>
To italicize all elements with the word barren in their class attribute, you write:
span[class~="barren"] {font-style: italic;}
This rule's selector will match the first two elements in the example markup and thus
italicize their text, as shown in Figure 1-11 . This is the same result we would expect
from writing span.barren {font-style: italic;} .
Figure 1-11. Selecting elements based on portions of attribute values
So why bother with the tilde-equals attribute selector in HTML? Because it can be used
for any attribute, not just class . For example, you might have a document that contains
a number of images, only some of which are figures. You can use a partial-match value
attribute selector aimed at the title text to select only those figures:
img[title~="Figure"] {border: 1px solid gray;}
This rule will select any image whose title text contains the word Figure . Therefore,
as long as all your figures have title text that looks something like “Figure 4. A bald-
headed elder statesman,” this rule will match those images. For that matter, the selector
img[title~="Figure"] will also match a title attribute with the value “How to Figure
Out Who's in Charge.” Any image that does not have a title attribute, or whose
title value doesn't contain the word “Figure,” won't be matched.
Matching a substring within an attribute value
Sometimes you want to select elements based on a portion of their attribute values, but
the values in question aren't space-separated lists of words. In these cases, you can use
the form [att*="val"] to match substrings that appear anywhere inside the attribute
values. For example, the following CSS matches any span element whose class attribute
contains the substring cloud , so both “cloudy” planets are matched, as shown in Fig-
ure 1-12 .
Search WWH ::

Custom Search