How do CSS attribute selectors match exact values, prefixes, and word lists?
Quick answer
Use [attr=value] for an exact value, ^= for a prefix, $= for a suffix, and *= for text anywhere inside a value. Use ~= to match one whole word in a whitespace-separated list. The similar-looking |= matches the exact value or that value followed immediately by a hyphen. Add [attr] when you only need to test whether an attribute exists. [S1]
The question, the details, the next step.
A practical checklist
Write down a representative attribute value from the markup.
Choose
=for the whole value,^=for a prefix,$=for a suffix, or*=for contained text.Choose
~=for one whole whitespace-separated word; do not substitute*=if partial matches are unwanted.Use
|=only when the match is the exact value or that value followed immediately by a hyphen.Use
[attr]for presence alone, and consideriorswhen ASCII case behavior matters.
A few more useful answers
Why does `[data-label~="warning"]` not match `data-label="warning-extra"`?
Because ~= looks for an exact word in a whitespace-separated list, and warning-extra is a different word. Use *= only if matching that character sequence inside a longer value is intended. [S1]
Does `[lang|="en"]` match any value that starts with `en`?
No. It matches the exact value en or a value where en is followed immediately by a hyphen, such as en-GB; it does not match english. [S1]
Does `[data-kind]` require the attribute to have a nonempty value?
It tests whether the attribute is present, not whether it has a particular value. Use a value-matching selector when the content of the attribute matters. [S1]
Sources
References used for this guide.
- [S1] Attribute selectors — CSS reference — MDN developer.mozilla.org · Checked
