Join MDN and developers like you at Mozilla's View Source conference, 12-14 September in Berlin, Germany. Learn more at https://viewsourceconf.org

Attribute selectors Redirect 1

Summary

Attribute selectors select an element using the presence of a given attribute or attribute value.

[attr]
Represents an element with an attribute name of attr.
[attr=value]
Represents an element with an attribute name of attr and whose value is exactly "value".
[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
[attr|=value]
Represents an element with an attribute name of attr. Its value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D). It can be used for language subcode matches.
[attr^=value]
Represents an element with an attribute name of attr and whose value is prefixed by "value".
[attr$=value]
Represents an element with an attribute name of attr and whose value is suffixed by "value".
[attr*=value]
Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.

Example

/* All spans with a "lang" attribute are bold */
span[lang] {font-weight:bold;}
 
/* All spans in Portuguese are green */
span[lang="pt"] {color:green;}

/* All spans in US English are blue  */
span[lang~="en-us"] {color: blue;}

/* Any span in Chinese is red, matches simplified (zh-CN) or traditional (zh-TW) */
span[lang|="zh"] {color: red;}

/* All internal links have a gold background */
a[href^="#"] {background-color:gold}

/* All links to urls ending in ".cn" are red */
a[href$=".cn"] {color: red;}

/* All links to with "example" in the url have a grey background */
a[href*="example"] {background-color: #CCCCCC;}
<div class="hello-example">
    <a href="http://example.com">English:</a>
    <span lang="en-us en-gb en-au en-nz">Hello World!</span>
</div>
<div class="hello-example">
    <a href="#portuguese">Portuguese:</a>
    <span lang="pt">Olá Mundo!</span>
</div>
<div class="hello-example">
    <a href="http://example.cn">Chinese (Simplified):</a>
    <span lang="zh-CN">世界您好!</span>
</div>
<div class="hello-example">
    <a href="http://example.cn">Chinese (Traditional):</a>
    <span lang="zh-TW">世界您好!</span>
</div>

Specifications

Specification Status Comment
CSS Selectors Level 3 Recommendation  
CSS 2.1 Recommendation  
CSS 1 Recommendation  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 1.0 (1.7 or earlier) 7 9 3
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 1.0 (1) ? ? ?

References

Document Tags and Contributors

 Last updated by: Sheppy,