HTML and CSS Reference
In-Depth Information
Figure 1-12. Selecting elements based on substrings within attribute values
span[class*="cloud"] {font-style: italic;}
<span class="barren rocky">Mercury</span>
<span class="cloudy barren">Venus</span>
<span class="life-bearing cloudy">Earth</span>
As you can imagine, there are many useful applications for this particular capability.
For example, suppose you wanted to specially style any links to the O'Reilly Media
website. Instead of classing them all and writing styles based on that class, you could
simply write the following rule:
a[href*=""] {font-weight: bold;}
Of course, you aren't confined to the class and href attributes. Any attribute is up for
grabs here. title , alt , src , id … you name it, you can style based on a substring within
an attribute's value. The following rule draws attention to any spacer GIF in an old-
school table layout (plus any other image with the string “space” in its source URL):
img[src*="space"] {border: 5px solid red;}
The matches are exact: if you include whitespace in your selector, then whitespace must
also be present in an attribute's value. The attribute names and values must be case-
sensitive only if the underlying document language requires case sensitivity.
Matching a substring at the beginning of an attribute value
In cases where you want to select elements based on a substring at the beginning of an
attribute value, then the attribute selector pattern [att^="val"] is what you're seeking.
This can be particularly useful in a situation where you want to style types of links
differently, as illustrated in Figure 1-13 .
a[href^="https:"] {font-weight: bold;}
a[href^="mailto:"] {font-style: italic;}
Figure 1-13. Selecting elements based on substrings that begin attribute values
Another use case is when you want to style all images in an article that are also figures,
as in the figures you see throughout this text. Assuming that the alt text of each figure
begins with text in the pattern “Figure 5”—which is an entirely reasonable assumption
in this case—then you can select only those images as follows:
Search WWH ::

Custom Search