CSS: Selector: Match Attribute Name or Value

By Xah Lee. Date: . Last updated: .

These let you match a html/xml attribute and or its value.

Match a Attribute Name

tag[attr]

Match element of name tag that has attribute attr.

x1[x2] {}

matches

<x1 x2="x309"></x1>

Match a Attribute and Its Value

tag[attr="val"]

Match tag, has attribute attr, value val.

a[b="c"] {}

matches

<a b="c"></a>

Match Parts of Attribute Value

tag[attr^="val"]

Match tag, has attribute attr, value begins with val.

tag[attr$="val"]

Match tag, has attribute attr, value ends with val.

tag[attr*="val"]

Match tag, has attribute attr, value contains val.

/* Color all links to Wikipedia red. */
a[href*="wikipedia.org/"] {color:red;}

Match Attribue Value that Has Space or Hyphen

tag[attr~="val"]

Match tag, has attribute attr, value is a list of space-separated values, one of which is exactly equal to val.

Usually used for HTML Class Attribute.

tag[attr|="val"]

Match tag, has attribute attr, value is val, or begin with val and is immediately followed by a hyphen.

Often used for lang attributes such as lang="zh-Hans" for simplified chinese and lang="zh-Hant" for traditional Chinese.

/* any p tag, attribute zz, value is x or start with x- */
p[zz|="x"] {
color:red;
}
<p zz="x">match</p>
<p zz="x-">match</p>
<p zz="x-3">match</p>
<p zz="x-4">match</p>

Make Case-Insensitive

/* make mp3 audio links with a music symbol */
a[href$=".mp3" i]:before {
content:"๐ŸŽตย ";
}
<a href="xyz.MP3">xyz.mp3</a>

Omitting Tag Name

The tag name can be omitted.

[xyz]

is the same as

*[xyz]

which matches any tag.

Multiple Attribute Selector

The attribute selector can be combined. For example:

p[x1="1"][x2="2"] {color:red;}

matches

<p x1="1" x2="2">something</p>

CSS Selectors