CSS Attribute Selectors
So far, we’ve explored the basics of CSS selectors: targeting elements by tag, class, or ID; combining selectors; styling multiple classes; grouping rules; and following the document hierarchy with child and sibling selectors.
Now, let’s dive into attribute selectors. These allow you to style elements based on the presence or value of their HTML attributes. In the next sections, we’ll move on to pseudo-classes and pseudo-elements.
Attribute Presence Selectors
The simplest attribute selector checks whether an element has a specific attribute, regardless of its value.
Code Block Loading...
This rule targets every <p> tag that includes an id attribute.
Exact Attribute Value Selectors
You can also match elements whose attribute equals a specific value using the = operator.
Code Block Loading...
Only <p> elements with id="my-id" will be styled.
Partial Attribute Value Selectors
Beyond exact matches, CSS provides several operators to match portions of attribute values:
| Operator | Meaning | Example |
| *= | Attribute contains the substring | p[id*='section'] |
| ^= | Attribute starts with the substring | p[id^='intro'] |
| $= | Attribute ends with the substring | p[id$='footer'] |
| |= | Attribute starts with substring followed by a dash, or equals substring | p[class ='lang'] |
| ~= | Attribute contains substring as a separate word (space-separated) | p[class~='highlight'] |
Case Sensitivity
By default, all these checks are case-sensitive.
To make them case-insensitive, add an i flag before the closing bracket:
Code Block Loading...
Browser support for this feature is widespread but not universal. You can check compatibility at Can I Use.
Key Takeaways
- Attribute selectors let you style elements based on their attributes.
- Use
[]for presence,=for exact matches, and operators like*=or^=for partial matches. - Remember: checks are case-sensitive unless you add the
iflag.
CSS attribute selectors with complete HTML and CSS example
Code Block Loading...