CSS Attribute Selectors - Match Elements by Attributes
Complete guide to CSS attribute selectors: presence, exact match, starts-with, ends-with, contains, and word match. Style links, inputs, and data attributes with precision.
Detailed Explanation
CSS Attribute Selectors
Attribute selectors let you target elements based on the presence or value of HTML attributes. They are powerful for styling form elements, links, and elements with data attributes.
Selector Variants
| Selector | Matches |
|---|---|
[attr] |
Elements that have the attribute |
[attr="val"] |
Attribute equals exactly |
[attr^="val"] |
Attribute starts with |
[attr$="val"] |
Attribute ends with |
[attr*="val"] |
Attribute contains substring |
[attr~="val"] |
Attribute word list contains |
| `[attr | ="val"]` |
Practical Examples
Style external links differently:
a[href^="https://"] {
padding-right: 16px;
background: url(external-icon.svg) right center no-repeat;
}
Style file download links by extension:
a[href$=".pdf"] { color: red; }
a[href$=".zip"] { color: green; }
a[href$=".doc"] { color: blue; }
Style inputs by type:
input[type="email"],
input[type="url"] {
font-family: monospace;
}
Target data attributes:
[data-theme="dark"] {
background: #1a1a2e;
color: #eee;
}
Case Sensitivity
By default, attribute value matching is case-sensitive. Add the i flag for case-insensitive matching:
[type="text" i] { /* matches TEXT, Text, text */ }
Specificity
All attribute selectors have the same specificity as a class selector: (0, 1, 0).
Use Case
Attribute selectors are indispensable for styling forms (targeting input types), handling external vs internal links, working with data attributes for JavaScript-driven state, and building accessible components. They are especially useful when you cannot add classes to elements, such as when working with third-party HTML or CMS-generated content.