Attribute selectors – CSS: Cascading Style Sheets

The CSS attribute selector matches elements based on the presence or value of a given attribute.

a[title] { color: purple; } a[href=”https://example.org”] { color: green; } a[href*=”example”] { font-size: 2em; } a[href$=”.org”] { font-style: italic; } a[class~=”logo”] { padding: 2px; } [attr] Represents elements with an attribute name of attr. [attr=value] Represents elements with an attribute name of attr whose value is exactly value. [attr~=value] Represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value. [attr|=value] Represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, – (U+002D). It is often used for language subcode matches. [attr^=value] Represents elements with an attribute name of attr whose value is prefixed (preceded) by value. [attr$=value] Represents elements with an attribute name of attr whose value is suffixed (followed) by value. [attr*=value] Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string. [attr operator value i] Adding an i (or I) before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range). [attr operator value s] This is an experimental API that should not be used in production code. Adding an s (or S) before the closing bracket causes the value to be compared case-sensitively (for characters within the ASCII range).

Links

CSS

a { color: blue; } a[href^=”#”] { background-color: gold; } a[href*=”example”] { background-color: silver; } a[href*=”insensitive” i] { color: cyan; } a[href*=”cAsE” s] { color: pink; } a[href$=”.org”] { color: red; } a[href^=”https”][href$=”.org”] { color: green; }

HTML

  • Internal link
  • Example link
  • Insensitive internal link
  • Example org link
  • Example https org link

Result

Languages

CSS

div[lang] { font-weight: bold; } div:not([lang]) { font-style: italic; } div[lang~=”en-us”] { color: blue; } div[lang=”pt”] { color: green; } div[lang|=”zh”] { color: red; } div[data-lang=”zh-TW”] { color: purple; }

HTML

Hello World!
Olá Mundo!
世界您好!
世界您好!
世界您好!

Result

HTML ordered lists

The HTML specification requires the type attribute to be matched case-insensitively due to it primarily being used in the element, trying to use attribute selectors to with the type attribute of an ordered list doesn’t work without the case-sensitive modifier.

CSS

ol[type=”a”] { list-style-type: lower-alpha; background: red; } ol[type=”a” s] { list-style-type: lower-alpha; background: lime; } ol[type=”A” s] { list-style-type: upper-alpha; background: lime; }

HTML

  1. Example list

Result

BCD tables only load in the browser

Source

Leave a comment

Your email address will not be published. Required fields are marked *