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

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

matches

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

Match a Attribute and Its Value

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

matches

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

but does not match

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

Match Attribute Value: {Beginning, End, Contains}

T[a^="v"]
Match T, has attribute a, value begins with v.
T[a$="v"]
Match T, has attribute a, value ends with v.
T[a*="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

T[a~="v"]
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.

T[a|="v"]
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

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

Match ID Attribute

T#v
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.

#v
same as [id="v"].

Omitting Tag Name

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

[xyz]

is the same as

*[xyz]

which matches any tag.

Example:

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

Multiple Attribute Selector

The attribute selector can be combined. For example:

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

matches

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

CSS Selectors (Syntax to Match HTML Elements)



CSS

Basics

Selectors

Color

Font

Text Decoration

Box Model

Box Decoration

Layout

Layers

Transform/Animation

Line Wrap

Misc