[attribute] matches any element that has that attribute at all, regardless of its value, while [attribute="value"] matches only elements where that attribute's value exactly equals the given string — additional operators extend this matching, like [attribute^="value"] for values starting with a given string, [attribute$="value"] for values ending with it, and [attribute*="value"] for values containing it anywhere. This is especially useful for styling form inputs based on their type attribute, like input[type="checkbox"], or targeting links based on their href, like a[href^="https://"] for external links, without needing a dedicated class added specifically for that purpose.
1Understanding Attribute Selectors
[attribute] matches any element that has that attribute at all, regardless of its value, while [attribute="value"] matches only elements where that attribute's value exactly equals the given string — additional operators extend this matching, like [attribute^="value"] for values starting with a given string, [attribute$="value"] for values ending with it, and [attribute*="value"] for values containing it anywhere. This is especially useful for styling form inputs based on their type attribute, like input[type="checkbox"], or targeting links based on their href, like a[href^="https://"] for external links, without needing a dedicated class added specifically for that purpose.
Use [target="_blank"], or [href^="http"] combined with excluding your own domain, to visually distinguish external links, like adding an icon, without needing to manually add a class to every single external link in your content.
input[type="checkbox"] {
width: 20px;
height: 20px;
}2Practical Example
Here is a real-world application of Attribute Selectors showing how it is used in production CSS code.
a[href$=".pdf"] {
color: darkred;
}
<a href="report.pdf">Report</a>
<a href="page.html">Page</a>3Best Practices
Follow these guidelines when working with Attribute Selectors:
1. Use [type="..."] attribute selectors to style different form input types distinctly, like checkboxes versus text inputs, without needing extra classes
2. Use [href^="..."] or [href$="..."] to target links by their URL pattern, like external links or links to a specific file type, directly from the markup's existing attributes
3. Prefer a dedicated class over an attribute selector when the underlying attribute's value might change for unrelated reasons, since the styling would then unintentionally change with it
Tip: Use [target="_blank"], or [href^="http"] combined with excluding your own domain, to visually distinguish external links, like adding an icon, without needing to manually add a class to every single external link in your content.
input[type="checkbox"] {
width: 20px;
height: 20px;
}