CSS: Attribute Selectors

By Xah Lee. Date: . Last updated: .

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

Match a Attribute Name

Match element of name T that has attribute a.
x1[x2] {}


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

Match a Attribute and Its Value

Match T, has attribute a, value v.
a[b="c"] {}


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

but does not match

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

Match Attribute Value: {Beginning, End, Contains}

Match T, has attribute a, value begins with v.
Match T, has attribute a, value ends with v.
Match T, has attribute a, value contains v.
/* Color all links to Wikipedia red. */
a[href*="wikipedia.org/"] {color:red;}

Match Attribue Value that Has Space or Hyphen

Match T, has attribute a, value is a list of space-separated values, one of which is exactly equal to v.

Usually used for HTML Class Attribute.

Match T, has attribute a, value begin with v 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.

HTML Selector Syntax Shortcuts

The following are most often used for HTML. But they do not necessarily work for XML, such as SVG

Match Class Attribute

HTML only. Element T with class v.
Same as T[class~="v"]
HTML only. Any element with class v
Same as [class~="v"]

Match ID Attribute

same as T[id="v"].

note, normally you don't need the T, because ID attribute should be unique on a page. There is only one element with a given ID value.

same as [id="v"].

Omitting Tag Name

Note, the tag name can be omitted. e.g.


is the same as


which matches any tag.


/* add [Wikipedia] text to all links to Wikipedia  */
[href*="wikipedia.org/wiki/"]:after {
content:" [Wikipedia]";

Multiple Attribute Selector

The attribute selector can be combined. For example:

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


<xx x1="1" x2="2">tt</xx>

CSS Selectors (Syntax to Match HTML Elements)