
Attribute selectors match elements by the attributes written in their HTML. They are useful for groups such as required input fields, links to PDFs, or elements with a data attribute.
1. Attribute selector syntax
| Selector | Matches |
|---|---|
[attr] | Any element with the attribute. |
[attr="value"] | An exact value. |
[attr~="value"] | A space-separated word in the value. |
[attr|="en"] | Exactly en, or en followed by a hyphen. |
[attr^="value"] | A value beginning with the given text. |
[attr$="value"] | A value ending with the given text. |
[attr*="value"] | A value containing the given text. |
2. Examples
input[required] { border-color: #6751a3; }
a[class~="external"] { text-decoration-style: dotted; }
a[href^="https://"] { overflow-wrap: anywhere; }
a[href$=".pdf" i]::after { content: " (PDF)"; }The i flag requests an ASCII case-insensitive value comparison. A suffix selector examines the literal attribute. A URL ending in .pdf?download=1 does not end in .pdf.
3. Practice
How can you flag an image with no alt attribute?
img:not([alt]) { outline: 3px solid red; }. An intentionally empty alt="" on a decorative image still counts as a present attribute.
Write a rule to mark links to PDF files. Compare it with the example above and try uppercase extensions and URLs with query strings.
See also CSS pseudo-classes and pseudo-elements.