CSS Attribute Selectors: Precision Targeting
Classes and IDs are the bread and butter of CSS targeting, but what happens when you need to style elements based on their HTML attributesโlike styling all links pointing to PDFs, or inputs of a specific type? That's where CSS Attribute Selectors come in.
The Basic Forms
Attribute selectors live inside square brackets [].
- Presence:
[attr]- Matches any element that simply *has* the attribute. Example:[disabled]targets all disabled inputs or buttons, regardless of value. - Exact Match:
[attr="value"]- Matches an element whose attribute exactly equals the string. Example:input[type="submit"]targets only submit buttons.
The Magic Wildcards
Often borrowed from regular expression logic, CSS allows string matching within attribute values.
- Starts With:
[attr^="value"]- Useful for finding elements where the attribute begins with a certain string. Example:a[href^="https"]. - Ends With:
[attr$="value"]- Targets the end of the string. Perfect for file extensions! Example:img[src$=".png"]. - Contains (Substring):
[attr*="value"]- The most flexible. Matches if the string appears *anywhere* in the attribute. Example:[class*="button-"]targets classes like "button-primary" and "large-button-red".
View Less Common Selectors (~= and |=)+
Space-Separated List: [attr~="value"] - Useful for matching individual words in attributes that contain space-separated values, like custom `data-tags="cool fast new"`.
Hyphen-Separated Prefix: [attr|="value"] - Rarely used, mostly for language codes. It matches an exact value, or a value immediately followed by a hyphen. Example: [lang|="en"] matches "en" and "en-US".
