The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1
Selectors 23

The final selector, the Language Attribute Selector, applies rules to ele-
ments that have an attribute matching the first argument in the selector,
the value of which is the second argument in the selector followed immedi-
ately by a hyphen. If that sounds weirdly specific, it’s because this selector
is really only intended to match language subcodes. The example markup
has two Spanish names, each of which has a lang attribute beginning with
es- although one is for Spain (es-ES) and the other is for Mexico (es-MX). To
select both of these, you use this code:

a[lang|='es'] { color: red; }

This selects all elements with lang attributes whose value begins with es,
regardless of their country values—that is, elements  and . You could
use this selector for any attributes with hyphen-separated values, but in the
great majority of cases, those will be language codes.

noTe The attribute names used here aren’t taken from the spec but from Eric Meyer’s book
CSS Pocket Reference (O’R eilly Media, 2011).

New Attribute Selectors in CSS3


You’ve seen how useful attribute selectors can be for finding exact or partial
values, but what if you want even more flexibility? CSS3’s new selectors pro-
vide flexibility with the power to match substrings within an attribute value.
This feature makes them especially great for applying rules to XML docu-
ments, which can often have more varied attribute values than HTML—
though they are still quite useful for HTML developers as well.

Beginning Substring Attribute Value Selector


The first new attribute selector—which, to avoid having to repeat that
mouthful of a title, I’ll refer to as the Beginning Selector—finds elements
whose chosen attribute begins with the string supplied to it as an argument.
It uses the caret (^) symbol to modify the equals sign in the selector. Here’s
the full syntax:

E[attr^='value'] {...}

This code looks for the supplied value at the beginning of the specified
attribute. To illustrate, consider the following example markup, showing a
list of three items, each of which contains a hyperlink with different (albeit
similar) values for the title attribute:

<li><a href="http://example.com/" title="Image Library">Example</a></li>
<li><a href="http://example.com/" title="Free Image Library">Example</a></li>
<li><a href="http://example.com/" title="Free Sound Library">Example</a></li>
Free download pdf