CSS Attribute Selectors
Attribute selectors allow you to select elements based on the presence or value of a given attribute. This is a powerful way to style elements without adding extra classes or IDs, keeping your markup clean and semantic.
Exact vs Partial Matching
The most common syntax is [attribute="value"], which requires an exact match. However, real power comes from partial matches:
- [attr^="val"]: Starts with (e.g., secure links
https). - [attr$="val"]: Ends with (e.g., file types
.pdf). - [attr*="val"]: Contains substring (e.g., part of a class name).
Common Use Cases
Forms: Target input types individually (`text` vs `submit` vs `checkbox`) without classes.
Links: Add icons to external links or download links based on the `href` attribute.
Debugging: Highlight elements with missing alt tags using img:not([alt]).
Best Practices
Attribute selectors have the same specificity as a class selector. They are robust and perform well in modern browsers. Use them to decouple your CSS from specific class names when the logic relates to the element's data or configuration.
