CSS: attribute selector

By Xah Lee. Date: . Last updated: .

Match Attribute Name

tag[attr]

Match element of name tag that has attribute attr.

tag here is compound selector, or none, which means the universal selector (* any tag).

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

a[data-accessed] {
 border: solid 1px grey;
}

matches

<a href="https://example.com/7161" data-accessed="2026-05-09" target="_blank" rel="noreferrer">https://example.com/7161</a>

Match Attribute Name and Value

tag[attr="val"]

Match tag, has attribute attr, value val.

tag is optional.

button[type="button"] {
 margin: 1ex;
}

matches

<button id="x5685" type="button">Random</button>

Match Parts of Attribute Value

Match Beginning of Attribute Value

tag[attr^="val"]

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

tag is optional.

/* color span tag with class name starting with x- */
span[class^="x-"] {
 color: red;
}

Match End of Attribute Value

tag[attr$="val"]

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

tag is optional.

Match Substring of Attribute Value

tag[attr*="val"]

Match tag, has attribute attr, value contains val.

tag is optional.

/* 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.

tag is optional.

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.

tag is optional.

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

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

Case-Insensitive Match on Attribute Value

in any of the attribute selector, you can add a i before the right square bracket, to indicate case-insensitive match for the value part. i can also be capital I e.g.

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

Multiple Attribute Selector

Match Attribute that Does Not Exist

/* match a pre tag that does not have class attribute */
pre:not([class]) {
 color: red;
}

CSS, Selectors

simple selectors
selector list
relationship selectors (combinators)
special selector
misc

HTML class attribute