CSS Attribute Selectors
Attribute selectors in CSS let you target elements by the presence or value of their attributes, like type
, href
, target
, lang
, etc.
This makes your CSS smarter and more dynamic — no need for extra classes!
✅ Basic Syntax
selector[attribute] {
/* styles */
}
📌 Common Attribute Selector Types
Selector | Meaning |
---|---|
[attr] | Element with the attribute (any value) |
[attr="value"] | Exact match |
[attr~="value"] | Value in space-separated list |
`[attr | =”value”]` |
[attr^="value"] | Starts with value |
[attr$="value"] | Ends with value |
[attr*="value"] | Contains value |
🎯 Examples
1. Existence Only
input[required] {
border: 1px solid red;
}
Matches any <input>
with the required
attribute.
2. Exact Match
input[type="email"] {
background-color: #f0f8ff;
}
Only targets <input type="email">
.
3. Space-separated List
div[class~="highlight"] {
background: yellow;
}
Matches: <div class="note highlight warning">
✅
Not: <div class="highlighted">
❌
4. Hyphen-separated Prefix
p[lang|="en"] {
font-style: italic;
}
Matches: lang="en"
, lang="en-US"
, etc.
5. Starts With
a[href^="https://"] {
color: green;
}
Targets all secure links.
6. Ends With
img[src$=".png"] {
border: 1px solid #ccc;
}
Selects only PNG images.
7. Contains Value
a[href*="login"] {
font-weight: bold;
}
Targets links like href="/user/login"
.
🔐 Real Use Cases
- Styling external links
- Targeting form fields by type
- Image format–based styling
- Language-based formatting
⚠️ Best Practices
- Attribute selectors are powerful, but avoid overuse on large DOMs — can affect performance.
- Prefer exact or starts-with match for performance.
- Combine with class or tag selectors when possible for specificity.
input[type="checkbox"]:checked {
/* safe and fast */
}