CSS: Selector: Match Attribute

By Xah Lee. Date: . Last updated: .

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

Match Attribute Name

tag[attr]

Match element of name tag that has attribute attr.

๐Ÿ’ก TIP: the tag name or attribute names need not be valid HTML names. Useful for XML such as SVG and HTML5 Custom Data Attribute.

aaa[bbb] {color:red;}

matches

<aaa bbb="x309">body</aaa>

Match Attribute Name and Value

tag[attr="val"]

Match tag, has attribute attr, value val.

aaa[bbb="ccc"] {color:red;}

matches

<aaa bbb="ccc">body</aaa>

Match Parts of Attribute Value

Match Beginning of Attribute Value

tag[attr^="val"]

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

/* color span tag with class name starting with name_ */
span[class ^="name_"]

Match End of Attribute Value

tag[attr$="val"]

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

Match Substring of Attribute Value

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>

Case-Insensitive Match on Attribute Value

/* 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[aaa="1"][bbb="2"] {color:red;}

matches

<p aaa="1" bbb="2">something</p>

CSS, Selectors