In the previous chapter I detailed the various CSS attribute selectors, which I will now quickly recap. Selectors are used in CSS to match HTML elements, and there are 10 different types, as detailed in Table 19-1.
Selector type | Example |
Universal selector | |
Type selectors | |
Class selectors | |
ID selectors | |
Descendant selectors | |
Child selectors | |
Adjacent sibling selectors | |
Attribute selectors | |
Pseudoclasses | |
Pseudoelements | |
The CSS3 designers decided that most of these selectors work just fine the way they are, but three enhancements have been made so that you can more easily match elements based on the contents of their attributes.
In CSS2 you can use a selector such as a[href='info.htm']
to match the string
'info.htm'
when found in an href
attribute, but there’s no way to match
only a portion of a string. However, CSS3 comes to the rescue with three
new operators: ^
, $
, and *
.
If one of these directly precedes the =
symbol, you can match the start, end, or any
part of a string, respectively.
For example, the following will match any href
attribute whose value begins with the
string 'http://website'
:
a[href^='http://website']
Therefore, the following element will match:
<a href='http://website.com'>
But this will not:
<a href='http://mywebsite.com'>
To match only at the end of a string, you can use a selector
such as the following, which will match any img
tag whose src
attribute ends with '.png'
:
img[src$='.png']
For example, the following will match:
<img src='photo.png' />
But this will not:
<img src='snapshot.jpg' />
To match a substring anywhere in the attribute, you can use a
selector such as the following, which will find any links on a page
that have the string 'google'
anywhere within them:
a[href*='google']
For example, this HTML segment will match:
<a href='http://google.com'>
while this segment will not:
<a href='http://gmail.com'>