HTML and CSS Reference
In-Depth Information
It is possible to match multiple attribute values or even pieces of the attribute values.
For example, to match a value in a space-separated list, you might use a rule like this:
p[title~="Larry"] {font-style: italic;}
This rule would match
<p title="Larry Curly and Moe">
This is italic.
</p>
<p title="Larry">
This is italic.
</p>
<p title="Larry-The-Stooge">
This is not italic.
</p>
To match an attribute value separated by dashes, which is common in language values
(for example,
en-uk
,
en-us
, and so on), use a rule like this:
p[lang|="en"] {color: red;} /* English text in red */
This rule would then affect English paragraphs but not paragraphs that have no language
specified or a different value than an English variation:
<p lang="en">
This is English and red.
</p>
<p lang="en-uk">
This is British English and red.
</p>
<p>
Not red no lang specified.
</p>
<p lang="fr">
C'est Francais. (Not red)
</p>
Later we will see an alternate form of language selection using a CSS3 pseudo-class
called
:lang()
. We'll save that for later when we discuss other pseudo-classes, but while
we're on the topic of CSS3, let's see what attribute selection possibilities this emerging
specification introduces.
CSS3 Attribute Selectors
CSS3 introduces a number of new attribute selectors. For example, you can now match
attributes that start with a particular value using
[attr^=value]
. Here we match
paragraphs that have
title
attributes that start with “Start match”
p [title^="Start match"] {background-color: red;}
and apply them to the following markup:
<p title="Start match">
This should be red.
</p>
<p title="No Start Match">
This should not be red.
</p>
Using
[attr$=value]
, we can match the end of an attribute value. For example, here
we match paragraphs with
title
attributes that end with “match end”
p.group4[title$="match end"] {background-color: red;}
which is demonstrated with this markup:
<p class="group4" title="This should match end">
This should be red.
</p>
<p class="group4" title="This won't match end!">
This shouldn't be red.
</p>