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

(C. Jardin) #1
Selectors 27

You may notice that this selector is somewhat similar to the Partial
Attribute Value Selector from CSS2, and, indeed, in this example, they are
interchangeable:

a[title~='image'] {...}

But the two selectors differ in a major way. In the example markup,
with CSS3, you could match this element using just a substring:

a[title*='im'] {...}

The Partial Attribute Value Selector, however, requires that you enter
a value that matches a full item in a space-separated list—in the example
that would be either free, image, or library—so the im value would not be
matched anywhere in the markup when using the CSS2 selector.
To continue with the examples provided for the first two attribute selec-
tors, the Arbitrary Selector is also handy for adding file-type icons to URIs
that have parameters at the end. Consider this fairly typical URI:

<a href="http://example.com/example.pdf?foo=bar">Example</a>

If you use the Ending Selector with a value of pdf, this element would not
be recognized as a valid target, even though the file type is a PDF, because
the value does not appear at the very end of the string. Providing the same
value using the Arbitrary Selector does the trick, however; the .pdf sub-
string value occurs within the specified attribute, so the icon is applied.

a[href*='.pdf'] { background-image: url('pdf.svg'); }

This selector is the most flexible of the three new attribute selectors as
it can match substrings no matter where they appear within strings. But this
extra flexibility means you must take more care when defining the values
provided to the selector; simple combinations of letters are far more likely
to occur when you can match anywhere within a string—which is the rea-
son I used it to search for .pdf (the file extension) rather than pdf (the com-
mon abbreviation).

Attribute Selectors


You can also chain multiple selectors together, which allows you to be really
specific. Using multiple selectors, you can create rules to apply to attributes
with values defined for the start, end, and anywhere in between. Imagine,
for example, that you had links to two files with identical names but that
were located in different folders:

<p><a href="http://example.com/folder1/file.pdf">Example</a></p>
<p><a href="http://example.com/folder2/file.pdf">Example</a></p>
Free download pdf