Most CSS selectors target elements by their name, class, or ID.
For example, you might style every <p> element or every element with the class .button. Sometimes, though, you need to be more specific.
In such cases you can use attribute selectors.
With an attribute selector you select elements based on whether they have a specific HTML attribute or an attribute holding a specific value.
Using attribute selectors helps you develop CSS that is more focused in what an element does, rather than what the element’s “identity” is.
A basic attribute selector
Let’s see a simple example:
This selector targets every <input> element that has a required attribute.
For example:
Only the first input matches the selector because it includes the required attribute.
You can also target a specific attribute value.
Now CSS selects only inputs where type is email.
You Can Match only a part of an attribute value
CSS provides several operators for making more precise matches. The $= operator checks the end of the href value, meaning that a link like <a href="guide.pdf"> would be a match.
For example, this selects links that point to PDF files:
You can also use the ^= operator to check the start of the attribute value.
You can use it to target external links that start with https://:
Here, ^= means “starts with.”
Or using the *=operator to check if the attribute contains a specific piece of text anywhere in its value.
This matches all links where href contains "programmer":
All three match because "programmer" is included somewhere inside the href value.
When should you use attribute selectors?
Attribute selectors are useful for forms, links, buttons and elements in general where an attribute describe the element. They keep your HTML code cleaner because you don’t have to create a new class for every small styling rule.