Attribute selectors allow us to select HTML elements based on their attributes. This provides more precise and flexible styling, especially for forms and links.
Attribute selectors can be used in several forms: existence check, exact match, or partial matches (starts with, ends with, contains).
| Selector | Description |
|---|---|
| [attr] | Selects all elements that have the specified attribute. |
| [attr="value"] | Selects elements whose attribute exactly matches the given value. |
| [attr^="value"] | Selects elements whose attribute starts with the given value. |
| [attr$="value"] | Selects elements whose attribute ends with the given value. |
| [attr*="value"] | Selects elements whose attribute contains the given substring. |
The simplest attribute selectors are based on attribute existence or exact matches. These are often used to target links or form fields.
In the following example, we select links and text fields based on attributes:
Advanced attribute selectors allow partial matches. For example, we can specify that a link starts with https, ends with .pdf, or contains a specific word.
Attribute selectors are powerful, but overuse can hurt performance. Here are some recommendations:
✨ Ask Lara — your AI study partner
Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.
Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.