
Attr Selectors in CSS
? CSS Attribute Selectors ([attr]
)
Attribute selectors in CSS allow you to target HTML elements based on their attributes or attribute values — not just classes or IDs. They're powerful for selecting dynamic or form-related elements.
? Basic Syntax
element[attribute] { /* styles */ }element[attribute="value"] { /* exact match */ }
? Common Types of Attribute Selectors
Selector | Matches Example |
---|---|
[attr] | Any element with the attribute |
[attr="value"] | Exact match |
[attr~="value"] | Space-separated value list (like class ) |
`[attr | ="value"]` |
[attr^="value"] | Starts with value |
[attr$="value"] | Ends with value |
[attr*="value"] | Contains value |
? Examples
1. Match any element with disabled
:
input[disabled] { background-color: #eee;}
2. Exact match:
a[target="_blank"] { color: red;}
3. Space-separated list (like class):
div[class~="featured"] { border: 2px solid gold;}
4. Value starts with:
a[href^="https://"] { font-weight: bold;}
5. Value ends with:
img[src$=".jpg"] { border-radius: 8px;}
6. Value contains:
a[href*="example"] { text-decoration: underline;}
? Notes:
Attribute selectors are case-sensitive by default (but not always in HTML).
They are commonly used for forms, accessibility attributes, and dynamic selectors.
Can be combined with classes or elements:
input[type="checkbox"].active { /* ... */ }
Would you like a practical demo (e.g., custom styles for file inputs, buttons, or tooltips)?