UX Design and Development course

Attribute selectors

Selecting 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 CSS

/* 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;}

Example HTML

<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>

Use case example

Let's say that you want to display all your internal links different from your external links. Old logic says that you would use JavaScript to search the DOM for queues. Attribute selectors give you this power for free.

p
  a(href="/internal/path.html") click here
p
  a(href="http://www.external.com") click here
a[href^="http"] {
  color: orange; }
  a[href^="http"]:after {
    display: inline-block;
    margin-left: 10px;
    content: "<- external"; }

Illustrated in this example, you will see that any URL that begins with http or https will get the new UI presented to the user.