CSS Attribute Selectors
Attribute selectors style elements based on their attributes and attribute values, without adding classes or IDs. For example, a[href^="http"]
targets links starting with "http". This provides flexibility, especially for content generated dynamically or without control over HTML classes.
Key Topics
- Attribute Presence ([attribute])
- Exact Match ([attribute="value"])
- Substring Matching ([attribute^=], [attribute$=], [attribute*=])
Example
img[alt]
selects images with an alt attribute, a[href^="https"]
selects links that begin with https.
a[href^="http"] {
color: blue;
}
img[alt] {
border: 2px solid green;
}
Explanation: Without adding extra classes, you can style external links or images with alt text, improving semantics and consistency.
Key Takeaways
- Flexibility: Style elements based on attributes alone.
- Semantic Targeting: Useful when you can’t modify HTML classes or IDs.
- Dynamic Content: Ideal for styling content generated by CMS or external sources.