#todayilearned

by @jm3 · aka John Manoogian3

Frequent, bite-size mini-milestone updates as I fast-forward merge* my front-end web development skills up to 2019 levels. Learn more

A catalog of CSS Attribute / Value Selectors

Posted at — Jul 12, 2019

CSS Attribute Value Selectors help you laser in on specific elements for styling based on their attribute values.

[…] → Attribute exists

/* matches elements with a foo attribute of any (or no) value */
[foo] {
  ...
}

Attribute foo exists — it may be a value-less boolean (like “autoplay”), or have any value.

= → Attribute value matches exactly

/* matches elements with a data-dongle attribute of "rubidium" */
[data-dongle="rubidium"] {
  ...
}

^= → Attribute value begins with …

/* matches SVG images with a viewBox value beginning with "0 " */
svg[viewBox^="0 "] {
  ...
}

Nerds who know Perl, ruby, PHP, or grep/unix will recoginze the $ character that denotes an end of string / end of line.

$= → Attribute value ends with …

/* matches elements with an href whose value ends in .pdf */
[href$=".pdf"] {
  ...
}

Nerds who know Perl, ruby, PHP, or grep/unix will recoginze the $ character that denotes an end of string / end of line.

~= → Attribute value contains word …

/* matches elements with a class list containing the WORD "discipline" */
[data-program~="discipline"] {
  ...
}

The one will match elements with the attribute attr only if val is one of a space-separated list of words contained in attr’s value. Note that even adjoining sentence style punctuation like commas will invalidate this, e.g. an element <div data-program="harsh discipline, no reprieve"> would not match the above selector.

*= → Attribute value contains substring …

/* matches elements with a fill @attr containing the string "flood" ANYWHERE */
[fill*="flood"] {
  ...
}

This matches elements with the attribute value containing the requested substring, whether it be at the beginning, middle, end, the entire string, etc.