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 */
}